<?php
declare(strict_types=1);

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

require_permission($conn, 'quick_service');

ensure_order_branch_column($conn);
ensure_order_bill_number_column($conn);
ensure_order_source_column($conn);
ensure_order_detail_item_note_column($conn);
ensure_payment_tender_columns($conn);
ensure_payment_slip_columns($conn);
ensure_car_profile_columns($conn);

$quickOrderId = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
$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);
$oldInput = pull_old_input();
$editingOrder = null;
$editingServiceIds = array();
$editingServiceNotes = array();
$editingPayments = array();
$paidBeforeAmount = 0.0;
$lastPaymentMethod = trim((string) ($_SESSION['booking_payment_method'] ?? 'cash'));

if ($quickOrderId) {
    $orderStmt = db_prepare($conn, "
        SELECT
            o.order_id,
            o.customer_id,
            o.car_id,
            o.bill_number,
            o.order_date,
            o.branch_name,
            o.status,
            o.payment_status,
            o.total_price,
            o.notes,
            c.name AS customer_name,
            c.phone,
            car.plate_number,
            car.province,
            car.brand,
            car.model,
            car.color,
            car.profile_image_path,
            car.profile_image_name
        FROM orders o
        LEFT JOIN customers c ON c.customer_id = o.customer_id
        LEFT JOIN cars car ON car.car_id = o.car_id
        WHERE o.order_id = ?
            AND o.order_source = 'quick_service'
        LIMIT 1
    ");
    $orderStmt->bind_param('i', $quickOrderId);
    $orderStmt->execute();
    $editingOrder = $orderStmt->get_result()->fetch_assoc();
    $orderStmt->close();

    if (!$editingOrder || !auth_can_access_branch($conn, (string) ($editingOrder['branch_name'] ?? ''))) {
        redirect_with_flash('quick_service.php', 'error', localized_flash_message('ไม่พบบิลพัก', 'Held bill was not found.'));
    }

    if ((string) ($editingOrder['payment_status'] ?? 'unpaid') === 'paid') {
        redirect_with_flash('quick_receipt.php?id=' . $quickOrderId, 'success', localized_flash_message('บิลควิกเซอร์วิสนี้ชำระครบแล้ว', 'Quick Service bill is already paid.'));
    }

    $serviceStmt = db_prepare($conn, "
        SELECT service_id, item_note
        FROM order_details
        WHERE order_id = ?
        ORDER BY detail_id ASC
    ");
    $serviceStmt->bind_param('i', $quickOrderId);
    $serviceStmt->execute();
    $serviceResult = $serviceStmt->get_result();

    while ($serviceRow = $serviceResult->fetch_assoc()) {
        $serviceId = (int) ($serviceRow['service_id'] ?? 0);
        $editingServiceIds[] = $serviceId;

        $itemNote = trim((string) ($serviceRow['item_note'] ?? ''));
        if ($serviceId > 0 && $itemNote !== '') {
            $editingServiceNotes[$serviceId] = $itemNote;
        }
    }

    $serviceStmt->close();

    $paymentStmt = db_prepare($conn, "
        SELECT payment_id, payment_method, amount, received_amount, change_amount, payment_date, note, slip_file_path, slip_file_name
        FROM payments
        WHERE order_id = ?
        ORDER BY payment_date DESC, payment_id DESC
    ");
    $paymentStmt->bind_param('i', $quickOrderId);
    $paymentStmt->execute();
    $paymentResult = $paymentStmt->get_result();

    while ($paymentRow = $paymentResult->fetch_assoc()) {
        $editingPayments[] = $paymentRow;
    }

    $paymentStmt->close();

    foreach ($editingPayments as $paymentRow) {
        $paidBeforeAmount += (float) ($paymentRow['amount'] ?? 0);
    }

    if (!empty($editingPayments)) {
        $lastPaymentMethod = trim((string) ($editingPayments[0]['payment_method'] ?? $lastPaymentMethod));
    }
}

if (!$quickOrderId && $openBillCustomerId > 0 && $openBillCarId > 0) {
    $prefillRecord = find_customer_record_by_ids($conn, $openBillCustomerId, $openBillCarId);

    if ($prefillRecord) {
        $oldInput['lookup_phone'] = (string) (($prefillRecord['plateNumber'] ?? '') !== '' ? $prefillRecord['plateNumber'] : ($prefillRecord['phone'] ?? ''));
        $oldInput['customer_mode'] = 'matched';
        $oldInput['customer_id'] = (string) ($prefillRecord['customerId'] ?? 0);
        $oldInput['car_id'] = (string) ($prefillRecord['carId'] ?? 0);
        $oldInput['customer_name'] = (string) ($prefillRecord['customerName'] ?? '');
        $oldInput['phone'] = (string) ($prefillRecord['phone'] ?? '');
        $oldInput['plate_number'] = (string) ($prefillRecord['plateNumber'] ?? '');
        $oldInput['province'] = (string) ($prefillRecord['province'] ?? '');
        $oldInput['brand'] = (string) ($prefillRecord['brand'] ?? '');
        $oldInput['model'] = (string) ($prefillRecord['model'] ?? '');
        $oldInput['color'] = (string) ($prefillRecord['color'] ?? '');
    }
}

$selectedServicesFromInput = array_values(array_unique(array_filter(array_map('intval', old_array($oldInput, 'service_ids')))));
$selectedServicesForQuery = !empty($selectedServicesFromInput) ? $selectedServicesFromInput : $editingServiceIds;

$services = service_catalog_rows($conn, array(
    'service_types' => array('main_service', 'sub_service'),
    'active_only' => true,
    'quick_service_only' => true,
    'include_inactive_ids' => $selectedServicesForQuery,
));

$servicesById = array();
$serviceGroups = array();

foreach ($services as $service) {
    $serviceId = (int) ($service['service_id'] ?? 0);
    $servicesById[$serviceId] = $service;

    $categoryName = trim((string) ($service['category_name'] ?? $service['category'] ?? 'General'));
    if (!isset($serviceGroups[$categoryName])) {
        $serviceGroups[$categoryName] = array();
    }

    $serviceGroups[$categoryName][] = $service;
}

ksort($serviceGroups, SORT_NATURAL | SORT_FLAG_CASE);

$selectedServices = !empty($selectedServicesFromInput) ? $selectedServicesFromInput : $editingServiceIds;
$selectedServiceNotes = array();
$serviceNotesSource = !empty(old_array($oldInput, 'service_notes')) ? old_array($oldInput, 'service_notes') : $editingServiceNotes;
foreach ($serviceNotesSource as $serviceId => $serviceNote) {
    $serviceId = (int) $serviceId;
    $serviceNote = trim((string) $serviceNote);

    if ($serviceId > 0 && $serviceNote !== '') {
        $selectedServiceNotes[$serviceId] = $serviceNote;
    }
}
$selectedServiceTotal = 0.0;
foreach ($selectedServices as $selectedServiceId) {
    if (isset($servicesById[$selectedServiceId])) {
        $selectedServiceTotal += (float) ($servicesById[$selectedServiceId]['price'] ?? 0);
    }
}

$paymentMethods = quick_service_payment_methods();
$selectedPaymentMethod = old_value($oldInput, 'payment_method', $lastPaymentMethod);
if (!array_key_exists($selectedPaymentMethod, $paymentMethods)) {
    $selectedPaymentMethod = 'cash';
}

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

$billTotalDefault = $editingOrder ? number_format((float) ($editingOrder['total_price'] ?? 0), 2, '.', '') : '';
$billTotalValue = old_value($oldInput, 'total_price', $billTotalDefault);
$totalPriceManual = $billTotalValue !== '' && abs((float) $billTotalValue - $selectedServiceTotal) > 0.009;
$receivedAmountValue = old_value($oldInput, 'received_amount', '');
$notesValue = old_value($oldInput, 'notes', (string) ($editingOrder['notes'] ?? ''));
$lookupQuery = old_value($oldInput, 'lookup_phone', old_value($oldInput, 'lookup_query'));
$quickServiceCustomerMode = old_value($oldInput, 'customer_mode');
$editingCustomerName = trim((string) ($editingOrder['customer_name'] ?? ''));
$editingPhone = trim((string) ($editingOrder['phone'] ?? ''));
$editingPlateNumber = trim((string) ($editingOrder['plate_number'] ?? ''));
$editingProvince = trim((string) ($editingOrder['province'] ?? ''));
$editingBrand = trim((string) ($editingOrder['brand'] ?? ''));
$editingModel = trim((string) ($editingOrder['model'] ?? ''));
$editingColor = trim((string) ($editingOrder['color'] ?? ''));

if ($quickServiceCustomerMode === '' && $editingOrder) {
    $quickServiceCustomerMode = $editingPhone === ''
        ? 'guest'
        : 'matched';
}

$quickServiceCustomerName = old_value($oldInput, 'customer_name', $editingCustomerName);
$quickServicePhone = old_value($oldInput, 'phone', $editingPhone);

if ($quickServiceCustomerMode === 'guest') {
    $quickServicePhone = '';
}

if ($quickServiceCustomerMode === 'guest') {
    $quickServiceCustomerName = trim($quickServiceCustomerName) !== ''
        ? $quickServiceCustomerName
        : ui_text('ลูกค้าทั่วไป', 'Guest');
}
$quickServicePlateNumber = old_value($oldInput, 'plate_number', $editingPlateNumber);
$quickServiceProvince = old_value($oldInput, 'province', $editingProvince);
$quickServiceBrand = old_value($oldInput, 'brand', $editingBrand);
$quickServiceModel = old_value($oldInput, 'model', $editingModel);
$quickServiceColor = old_value($oldInput, 'color', $editingColor);
$quickServiceCustomerId = (int) old_value($oldInput, 'customer_id', (string) ($editingOrder['customer_id'] ?? '0'));
$quickServiceCarId = (int) old_value($oldInput, 'car_id', (string) ($editingOrder['car_id'] ?? '0'));
$quickServiceVehiclePhoto = null;
if ($quickServiceCustomerId > 0 && $quickServiceCarId > 0) {
    $quickServiceVehiclePhoto = find_customer_record_by_ids($conn, $quickServiceCustomerId, $quickServiceCarId);
}
if (!$quickServiceVehiclePhoto && $editingOrder) {
    $quickServiceVehiclePhoto = $editingOrder;
}
$showQuickServiceFlow = $editingOrder !== null
    || $quickServiceCustomerMode !== ''
    || $quickServiceCustomerName !== ''
    || $quickServicePlateNumber !== '';
$quickServiceLookupMessage = '';
$quickServiceLookupState = '';

if ($showQuickServiceFlow) {
    if ($quickServiceCustomerMode === 'guest') {
        $quickServiceLookupMessage = ui_text('ระบุทะเบียนรถของลูกค้าทั่วไปเพื่อเริ่มงานควิกเซอร์วิส', 'Enter the plate number for the guest customer to continue.');
        $quickServiceLookupState = 'warning';
    } else {
        $quickServiceLookupMessage = ui_text('ดึงข้อมูลลูกค้าเรียบร้อยแล้ว', 'Customer data loaded.');
        $quickServiceLookupState = 'success';
    }
}

$heldBills = array();
$heldTypes = '';
$heldParams = array();
$heldWhere = array(
    "o.order_source = 'quick_service'",
    "o.status <> 'cancelled'",
    "o.payment_status <> 'paid'",
);
$heldBranchCondition = auth_branch_condition($conn, 'o', $heldTypes, $heldParams);
if ($heldBranchCondition !== '') {
    $heldWhere[] = $heldBranchCondition;
}
$heldWhereSql = implode(' AND ', $heldWhere);

$heldSql = "
    SELECT
        o.order_id,
        o.bill_number,
        o.order_date,
        o.branch_name,
        o.status,
        o.payment_status,
        o.total_price,
        o.updated_at
    FROM orders o
    WHERE {$heldWhereSql}
    ORDER BY o.updated_at DESC, o.order_id DESC
";

if ($heldTypes === '') {
    $heldResult = $conn->query($heldSql);
} else {
    $heldStmt = db_prepare($conn, $heldSql);
    $heldStmt->bind_param($heldTypes, ...$heldParams);
    $heldStmt->execute();
    $heldResult = $heldStmt->get_result();
}

if ($heldResult instanceof mysqli_result) {
    while ($row = $heldResult->fetch_assoc()) {
        $heldBills[] = $row;
    }
}

if (isset($heldStmt)) {
    $heldStmt->close();
}

$heldOrderIds = array_column($heldBills, 'order_id');
$heldServiceSummaryMap = order_service_summary_map($conn, $heldOrderIds);
$heldPaymentSummaryMap = order_payment_summary_map($conn, $heldOrderIds);

foreach ($heldBills as &$heldBill) {
    $orderId = (int) ($heldBill['order_id'] ?? 0);
    $serviceSummary = $heldServiceSummaryMap[$orderId] ?? array();
    $paymentSummary = $heldPaymentSummaryMap[$orderId] ?? order_payment_summary_defaults();
    $heldBill['service_names'] = (string) ($serviceSummary['service_names'] ?? '');
    $heldBill['item_count'] = (int) ($serviceSummary['item_count'] ?? 0);
    $heldBill['paid_amount'] = (float) ($paymentSummary['total_amount'] ?? 0);
}
unset($heldBill);

$qrAvailable = quick_service_qr_available($selectedBranchName, 'quick_service')
    || quick_service_qr_available('', 'quick_service');
$canAccessManageSystem = can_access_manage_system($conn);
$canReceiveQuickServicePayment = can_access($conn, 'quick_service_payment');
$canCancelHeldBill = can_access($conn, 'queue_cancel_open') || can_access($conn, 'quick_service');
$canDeletePartialPayment = $editingOrder && $canReceiveQuickServicePayment;
$currentBillLabel = $editingOrder
    ? ((string) (($editingOrder['bill_number'] ?? '') !== '' ? $editingOrder['bill_number'] : '#' . (int) $editingOrder['order_id']))
    : '';

$pageTitle = ui_text('ควิกเซอร์วิส', 'Quick Service');
$pageDescription = ui_text('สร้างบิลหน้าร้าน พักบิลค้างชำระ รับเงิน และพิมพ์ใบเสร็จโดยไม่ต้องส่งงานเข้าคิว', 'Create counter bills, hold unpaid bills, collect payment and print receipts without sending work into Queue.');
$manageSystemLabel = ui_text('จัดการระบบ', 'Manage System');
$newQuickBillLabel = ui_text('เปิดบิลด่วนใหม่', 'New quick bill');
$backToDashboardLabel = ui_text('กลับไปแดชบอร์ด', 'Back to dashboard');
$resumeHeldBillLabel = ui_text('กลับมาแก้บิลพัก', 'Resume held bill');
$branchLabel = ui_text('สาขา', 'Branch');
$createdLabel = ui_text('สร้างเมื่อ', 'Created');
$cancelBillLabel = ui_text('ยกเลิกบิล', 'Cancel bill');
$noQuickServiceItemsLabel = ui_text('ยังไม่มีรายการบริการที่เปิดใช้งานสำหรับควิกเซอร์วิส', 'No service items are enabled for Quick Service yet.');
$manageServicesLabel = ui_text('จัดการบริการ', 'Manage services');
$quickServiceItemsTitle = ui_text('รายการควิกเซอร์วิส', 'Quick service items');
$quickServiceItemsHelper = ui_text('เลือกรายการที่ขายหน้าสาขา ใช้พักบิลเมื่อยังไม่พร้อมชำระหรือยังชำระไม่ครบ', 'Choose the items sold at the branch counter. Use Hold bill when the customer is not ready to pay or has not paid the full amount yet.');
$heldBillSummaryLabel = ui_text('สรุปบิลพัก', 'Held bill summary');
$quickBillSummaryLabel = ui_text('สรุปบิลด่วน', 'Quick bill summary');
$serviceBranchLabel = ui_text('สาขาที่ให้บริการ', 'Service branch');
$selectBranchLabel = ui_text('เลือกสาขา', 'Select branch');
$selectedItemsLabel = ui_text('รายการที่เลือก', 'Selected items');
$itemCountLabel = ui_text('{count} รายการ', '{count} item(s)');
$serviceTotalLabel = ui_text('ยอดบริการ', 'Service total');
$billTotalLabel = ui_text('ยอดรวมบิล', 'Bill total');
$paidAlreadyLabel = ui_text('ชำระแล้ว', 'Paid already');
$balanceDueLabel = ui_text('ยอดค้างชำระ', 'Balance due');
$recognizedNowLabel = ui_text('รับรู้ยอดครั้งนี้', 'Recognized now');
$cashChangeLabel = ui_text('เงินทอน', 'Cash change');
$paymentMethodLabel = ui_text('วิธีชำระเงิน', 'Payment method');
$qrConfigMissingLabel = ui_text('ตั้งค่า QR สำหรับสาขาที่เลือก หรือใช้โปรไฟล์ค่าเริ่มต้นทุกสาขาเพื่อแสดงตัวอย่าง QR', 'Set QR configuration for the selected branch or use the all-branch default profile to display a QR preview.');
$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.');
$noQuickPaymentPermissionLabel = ui_text('คุณไม่มีสิทธิ์รับชำระควิกเซอร์วิส แต่ยังพักบิลหรืออัปเดตบิลได้', 'You do not have permission to receive Quick Service payment. You can still hold or update the bill.');
$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.');
$holdBillLabel = ui_text('พักบิล', 'Hold bill');
$paymentActionLabel = ui_text('ชำระเงิน', 'Payment');
$recordedPaymentsLabel = ui_text('ประวัติการรับชำระ', 'Recorded payments');
$recordCountHeldBillLabel = ui_text('{count} รายการในบิลพักนี้', '{count} record(s) on this held bill');
$noPaymentRecordedLabel = ui_text('ยังไม่มีการบันทึกรับชำระ', 'No payment recorded yet.');
$paidAmountLabel = ui_text('ชำระ', 'Paid');
$receivedAmountLabel = ui_text('รับเงิน', 'Received');
$changeAmountLabel = ui_text('เงินทอน', 'Change');
$deletePaymentConfirmLabel = ui_text('ลบรายการชำระเงินนี้ออกจากบิลพักหรือไม่', 'Delete this recorded payment from the held bill?');
$deletePaymentLabel = ui_text('ลบรายการชำระเงิน', 'Delete payment');
$heldBillsLabel = ui_text('บิลพัก', 'Held bills');
$heldBillsWaitingLabel = ui_text('{count} บิลที่รอชำระเงิน', '{count} bill(s) waiting for payment');
$noHeldBillLabel = ui_text('ไม่มีบิลควิกเซอร์วิสที่พักอยู่', 'No held Quick Service bill.');
$billLabel = ui_text('บิล', 'Bill');
$itemsLabel = ui_text('รายการ', 'Items');
$totalLabel = ui_text('รวม', 'Total');
$paidLabel = ui_text('ชำระแล้ว', 'Paid');
$balanceLabel = ui_text('คงค้าง', 'Balance');
$statusLabel = ui_text('สถานะ', 'Status');
$updatedLabel = ui_text('อัปเดตล่าสุด', 'Updated');
$actionLabel = ui_text('การทำรายการ', 'Action');
$resumeLabel = ui_text('เปิดต่อ', 'Resume');
$serviceItemFallbackLabel = ui_text('รายการบริการ', 'Service item');

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

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

<section class="page-hero">
    <div>
        <h1><?= e($pageTitle) ?></h1>
        <p><?= e($pageDescription) ?></p>
    </div>
    <div class="hero-actions">
        <?php if ($canAccessManageSystem): ?>
            <a class="button button-secondary" href="manage_system.php"><?= e($manageSystemLabel) ?></a>
        <?php endif; ?>
        <?php if ($editingOrder): ?>
            <a class="button button-secondary" href="quick_service.php"><?= e($newQuickBillLabel) ?></a>
        <?php endif; ?>
        <a class="button button-secondary" href="dashboard.php"><?= e($backToDashboardLabel) ?></a>
    </div>
</section>

<?php if ($editingOrder): ?>
    <section class="card quick-service-editor-note">
        <div>
            <h2 class="section-title"><?= e($resumeHeldBillLabel) ?> <?= e($currentBillLabel) ?></h2>
            <p class="helper"><?= e($branchLabel) ?> <?= e((string) ($editingOrder['branch_name'] ?? '-')) ?> / <?= e($createdLabel) ?> <?= e(format_datetime((string) ($editingOrder['order_date'] ?? ''))) ?></p>
        </div>
        <div class="quick-service-editor-meta">
            <?php if ($canCancelHeldBill): ?>
                <a class="button button-danger" href="cancel_bill.php?id=<?= (int) $editingOrder['order_id'] ?>&return_to=<?= e(urlencode('quick_service.php')) ?>"><?= e($cancelBillLabel) ?></a>
            <?php endif; ?>
            <span class="<?= e(status_class((string) ($editingOrder['status'] ?? 'waiting'))) ?>"><?= e(status_label((string) ($editingOrder['status'] ?? 'waiting'))) ?></span>
            <span class="<?= e(payment_status_class((string) ($editingOrder['payment_status'] ?? 'unpaid'))) ?>"><?= e(payment_status_label((string) ($editingOrder['payment_status'] ?? 'unpaid'))) ?></span>
        </div>
    </section>
<?php endif; ?>

<?php if (empty($services)): ?>
    <section class="empty-state">
        <?= e($noQuickServiceItemsLabel) ?>
        <div class="actions" style="justify-content: center; margin-top: 14px;">
            <a class="button" href="services.php"><?= e($manageServicesLabel) ?></a>
        </div>
    </section>
<?php else: ?>
    <form
        method="POST"
        action="../process/save_quick_service.php"
        enctype="multipart/form-data"
        data-booking-form
        data-quick-service-form="1"
        data-paid-before="<?= e(number_format($paidBeforeAmount, 2, '.', '')) ?>"
        data-qr-available="<?= $qrAvailable ? '1' : '0' ?>"
                        data-qr-endpoint="../process/quick_service_qr.php"
                        data-qr-scope="quick_service"
                        data-qr-branch="<?= e($selectedBranchName) ?>"
                    >
        <?= csrf_input('quick_service_save') ?>
        <?php if ($editingOrder): ?>
            <input type="hidden" name="quick_order_id" value="<?= (int) $editingOrder['order_id'] ?>">
        <?php endif; ?>
        <input type="hidden" id="customer_mode" name="customer_mode" value="<?= e($quickServiceCustomerMode) ?>">
        <input type="hidden" id="customer_id" name="customer_id" value="<?= $quickServiceCustomerId > 0 ? $quickServiceCustomerId : '' ?>">
        <input type="hidden" id="car_id" name="car_id" value="<?= $quickServiceCarId > 0 ? $quickServiceCarId : '' ?>">

        <section class="card booking-lookup-card">
            <div class="form-grid booking-lookup-grid">
                <div class="field">
                    <label for="lookup_phone"><?= ui_text('ค้นหาลูกค้าด้วยเบอร์โทรหรือทะเบียนรถ', 'Search customer by phone or plate') ?></label>
                    <input
                        id="lookup_phone"
                        name="lookup_phone"
                        type="text"
                        inputmode="text"
                        autocomplete="off"
                        value="<?= e($lookupQuery) ?>"
                        placeholder="0971234567 / 1234 / 5ขฮ8154"
                    >
                    <p class="helper"><?= ui_text('ค้นหาได้เฉพาะเบอร์โทรลูกค้าที่ตรงกันหรือทะเบียนรถที่ตรงเท่านั้น', 'Search works only with the exact customer phone number or exact plate number.') ?></p>
                </div>
            </div>

            <div class="actions booking-lookup-actions">
                <button
                    class="button app-action-button"
                    type="button"
                    data-customer-lookup
                ><?= app_button_content('search', ui_text('ค้นหา', 'Search')) ?></button>
                <button
                    class="button button-accent app-action-button"
                    type="button"
                    data-new-customer-trigger
                ><?= app_button_content('user', ui_text('ลูกค้าทั่วไป', 'Guest')) ?></button>
                <a class="button button-ghost app-action-button" href="<?= e($editingOrder ? 'quick_service.php?id=' . (int) $editingOrder['order_id'] : 'quick_service.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($quickServiceLookupState) ?>" aria-live="polite"><?= e($quickServiceLookupMessage) ?></div>
                <div class="lookup-results" data-lookup-results hidden></div>
            </div>
        </section>

        <div class="content-grid booking-flow-grid" data-booking-flow <?= $showQuickServiceFlow ? '' : 'hidden' ?>>
            <div class="grid">
                <section class="form-card">
                    <div class="section-head">
                        <div>
                            <h2 class="section-title"><?= ui_text('ข้อมูลลูกค้าและรถ', 'Customer and vehicle details') ?></h2>
                            <p class="helper"><?= ui_text('ควิกเซอร์วิสใช้ได้กับลูกค้าเดิมหรือโหมดลูกค้าทั่วไปเท่านั้น', 'Quick Service can use existing customers or Guest mode only.') ?></p>
                        </div>
                    </div>

                    <div class="form-grid">
                        <?php if ($quickServiceCustomerMode !== 'guest' && is_array($quickServiceVehiclePhoto)): ?>
                            <div class="field">
                                <label><?= e(ui_text('รูปโปรไฟล์รถ', 'Vehicle profile photo')) ?></label>
                                <div class="vehicle-profile-inline">
                                    <?= car_profile_photo_html($quickServiceVehiclePhoto, '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" data-quick-customer-primary>
                            <label for="customer_name"><?= ui_text('ชื่อลูกค้า', 'Customer name') ?></label>
                            <input
                                id="customer_name"
                                name="customer_name"
                                type="text"
                                value="<?= e($quickServiceCustomerName) ?>"
                                placeholder="<?= e(ui_text('ชื่อลูกค้าทั่วไป', 'Guest name')) ?>"
                            >
                        </div>

                        <div class="field" data-quick-guest-extra <?= $quickServiceCustomerMode === 'guest' ? 'hidden' : '' ?>>
                            <label for="phone"><?= ui_text('เบอร์โทร', 'Phone') ?></label>
                            <input id="phone" name="phone" type="text" value="<?= e($quickServicePhone) ?>" readonly>
                        </div>

                        <div class="field" data-quick-customer-primary>
                            <label for="plate_number"><?= ui_text('ทะเบียนรถ', 'Plate number') ?></label>
                            <input id="plate_number" name="plate_number" type="text" value="<?= e($quickServicePlateNumber) ?>" required>
                            <p class="helper"><?= ui_text('หากเลือกโหมดลูกค้าทั่วไป ต้องระบุทะเบียนรถก่อนเริ่มงาน', 'Guest mode requires a plate number before continuing.') ?></p>
                        </div>

                        <div class="field" data-quick-guest-extra <?= $quickServiceCustomerMode === 'guest' ? 'hidden' : '' ?>>
                            <label for="province"><?= ui_text('จังหวัด', 'Province') ?></label>
                            <input id="province" name="province" type="text" value="<?= e($quickServiceProvince) ?>" readonly>
                        </div>

                        <div class="field" data-quick-guest-extra <?= $quickServiceCustomerMode === 'guest' ? 'hidden' : '' ?>>
                            <label for="brand"><?= ui_text('ยี่ห้อ', 'Brand') ?></label>
                            <input id="brand" name="brand" type="text" value="<?= e($quickServiceBrand) ?>" readonly>
                        </div>

                        <div class="field" data-quick-guest-extra <?= $quickServiceCustomerMode === 'guest' ? 'hidden' : '' ?>>
                            <label for="model"><?= ui_text('รุ่น', 'Model') ?></label>
                            <input id="model" name="model" type="text" value="<?= e($quickServiceModel) ?>" readonly>
                        </div>

                        <div class="field" data-quick-guest-extra <?= $quickServiceCustomerMode === 'guest' ? 'hidden' : '' ?>>
                            <label for="color"><?= ui_text('สี', 'Color') ?></label>
                            <input id="color" name="color" type="text" value="<?= e($quickServiceColor) ?>" readonly>
                        </div>
                    </div>
                </section>

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

                    <div class="service-options">
                        <?php foreach ($serviceGroups as $categoryName => $serviceRows): ?>
                            <div class="service-group-head">
                                <h3><?= e($categoryName) ?></h3>
                            </div>

                            <?php foreach ($serviceRows as $service): ?>
                                <?php
                                $serviceId = (int) ($service['service_id'] ?? 0);
                                $checked = in_array($serviceId, $selectedServices, true) ? 'checked' : '';
                                $serviceType = (string) ($service['service_type'] ?? 'sub_service');
                                $serviceTypeLabel = service_type_options()[$serviceType] ?? $serviceType;
                                ?>
                                <label class="service-option compact-option">
                                    <input
                                        type="checkbox"
                                        name="service_ids[]"
                                        value="<?= $serviceId ?>"
                                        data-service-option
                                        data-price="<?= e((string) ($service['price'] ?? 0)) ?>"
                                        <?= $checked ?>
                                    >
                                    <span>
                                        <strong><?= e((string) ($service['service_name'] ?? $serviceItemFallbackLabel)) ?></strong>
                                        <?php if ($description = trim((string) ($service['description'] ?? ''))): ?>
                                            <span class="muted"><?= e($description) ?></span>
                                        <?php endif; ?>
                                        <span class="service-meta">
                                            <span><?= e($serviceTypeLabel) ?></span>
                                            <span><?= format_money($service['price'] ?? 0) ?> THB</span>
                                        </span>
                                        <?php $serviceNote = trim((string) ($selectedServiceNotes[$serviceId] ?? '')); ?>
                                        <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 endforeach; ?>
                        <?php endforeach; ?>
                    </div>
                </section>
            </div>

            <aside class="grid summary-panel">
                <section class="card booking-summary-card">
                    <h2 class="section-title"><?= e($editingOrder ? $heldBillSummaryLabel : $quickBillSummaryLabel) ?></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) ?>" <?= $selectedBranchName === $branchName ? 'selected' : '' ?>>
                                    <?= e($branchName) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <p class="helper"><?= e($selectedItemsLabel) ?></p>
                    <p class="summary-total"><span data-selected-count>0</span> <?= e(ui_text('รายการ', 'item(s)')) ?></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($billTotalLabel) ?></label>
                        <input
                            id="total_price"
                            name="total_price"
                            type="number"
                            step="0.01"
                            min="0"
                            value="<?= e($billTotalValue) ?>"
                            data-total-price-input
                            data-manual="<?= $totalPriceManual ? '1' : '0' ?>"
                        >
                    </div>

                    <div class="quick-service-summary-grid">
                        <div>
                            <span><?= e($paidAlreadyLabel) ?></span>
                            <strong data-paid-before><?= format_money($paidBeforeAmount) ?></strong>
                        </div>
                        <div data-balance-due-card>
                            <span><?= e($balanceDueLabel) ?></span>
                            <strong data-balance-due><?= format_money(max(0.0, ($billTotalValue !== '' ? (float) $billTotalValue : $selectedServiceTotal) - $paidBeforeAmount)) ?></strong>
                        </div>
                        <?php if ($canReceiveQuickServicePayment): ?>
                            <div>
                                <span><?= e($recognizedNowLabel) ?></span>
                                <strong data-recognized-payment>0.00</strong>
                            </div>
                            <div data-change-field hidden>
                                <span><?= e($cashChangeLabel) ?></span>
                                <strong data-change-due>0.00</strong>
                            </div>
                        <?php endif; ?>
                    </div>

                    <?php if ($canReceiveQuickServicePayment): ?>
                        <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($qrConfigMissingLabel) ?></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(ui_text('คิวอาร์ชำระเงินควิกเซอร์วิส', 'Quick Service QR payment')) ?>" 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>
                    <?php else: ?>
                        <input type="hidden" name="payment_method" value="<?= e($selectedPaymentMethod) ?>">
                        <p class="helper"><?= e($noQuickPaymentPermissionLabel) ?></p>
                    <?php endif; ?>

                    <div class="field bill-note-field">
                        <label for="notes"><?= e($billNoteLabel) ?></label>
                        <textarea id="notes" name="notes" rows="4" placeholder="<?= e($billNotePlaceholder) ?>"><?= e($notesValue) ?></textarea>
                        <p class="helper"><?= e($billNoteHelperLabel) ?></p>
                    </div>

                    <div class="actions quick-service-actions <?= $canReceiveQuickServicePayment ? '' : 'is-single' ?>">
                        <button class="button button-secondary button-full" type="submit" name="submit_action" value="hold"><?= e($holdBillLabel) ?></button>
                        <?php if ($canReceiveQuickServicePayment): ?>
                            <button class="button button-accent button-full" type="submit" name="submit_action" value="pay" data-pay-submit><?= e($paymentActionLabel) ?></button>
                        <?php endif; ?>
                    </div>
                </section>

            </aside>
        </div>
    </form>

    <?php if ($editingOrder): ?>
        <section class="card quick-service-payment-history-card">
            <div class="section-head">
                <div>
                    <h2 class="section-title"><?= e($recordedPaymentsLabel) ?></h2>
                    <p class="helper"><?= e(strtr($recordCountHeldBillLabel, array('{count}' => (string) count($editingPayments)))) ?></p>
                </div>
            </div>

            <?php if (empty($editingPayments)): ?>
                <div class="empty-state quick-service-payment-empty"><?= e($noPaymentRecordedLabel) ?></div>
            <?php else: ?>
                <div class="quick-service-payment-history">
                    <?php foreach ($editingPayments as $payment): ?>
                        <?php
                        $paymentId = (int) ($payment['payment_id'] ?? 0);
                        $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'] ?? ''));
                        $paymentSlipViewUrl = $paymentId > 0 ? payment_slip_access_url($paymentId) : '';
                        $paymentSlipPath = trim((string) ($payment['slip_file_path'] ?? ''));
                        $paymentSlipPath = $paymentSlipPath !== '' ? $paymentSlipViewUrl : '';
                        $paymentSlipName = trim((string) ($payment['slip_file_name'] ?? ''));
                        ?>
                        <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($paidAmountLabel) ?> <?= format_money($paymentAmount) ?> THB</span>
                                    <span><?= e($receivedAmountLabel) ?> <?= format_money($paymentReceived > 0 ? $paymentReceived : $paymentAmount) ?> THB</span>
                                    <?php if ($paymentChange > 0): ?>
                                        <span><?= e($changeAmountLabel) ?> <?= format_money($paymentChange) ?> THB</span>
                                    <?php endif; ?>
                                </div>
                                <?php if ($paymentNote !== ''): ?>
                                    <p class="helper"><?= e($paymentNote) ?></p>
                                <?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>
                            <?php if ($canDeletePartialPayment): ?>
                                <form
                                    method="POST"
                                    action="../process/delete_quick_service_payment.php"
                                    class="quick-service-payment-delete"
                                    onsubmit="return confirm('<?= e($deletePaymentConfirmLabel) ?>');"
                                >
                                    <?= csrf_input('quick_service_payment_delete') ?>
                                    <input type="hidden" name="order_id" value="<?= (int) $editingOrder['order_id'] ?>">
                                    <input type="hidden" name="payment_id" value="<?= $paymentId ?>">
                                    <input type="hidden" name="return_to" value="<?= e('quick_service.php?id=' . (int) $editingOrder['order_id']) ?>">
                                    <button class="button button-danger" type="submit"><?= e($deletePaymentLabel) ?></button>
                                </form>
                            <?php endif; ?>
                        </article>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </section>
    <?php endif; ?>

    <section class="table-card quick-service-held-card">
        <div class="section-head" style="padding: 18px 18px 0;">
            <div>
                <h2 class="section-title"><?= e($heldBillsLabel) ?></h2>
                <p class="helper"><?= e(strtr($heldBillsWaitingLabel, array('{count}' => (string) count($heldBills)))) ?></p>
            </div>
        </div>

        <?php if (empty($heldBills)): ?>
            <div class="empty-state" style="margin: 18px;"><?= e($noHeldBillLabel) ?></div>
        <?php else: ?>
            <table class="quick-service-held-table">
                <thead>
                <tr>
                    <th><?= e($billLabel) ?></th>
                    <th><?= e($branchLabel) ?></th>
                    <th><?= e($itemsLabel) ?></th>
                    <th><?= e($totalLabel) ?></th>
                    <th><?= e($paidLabel) ?></th>
                    <th><?= e($balanceLabel) ?></th>
                    <th><?= e($statusLabel) ?></th>
                    <th><?= e($updatedLabel) ?></th>
                    <th><?= e($actionLabel) ?></th>
                </tr>
                </thead>
                <tbody>
                <?php foreach ($heldBills as $heldBill): ?>
                    <?php
                    $heldBillId = (int) ($heldBill['order_id'] ?? 0);
                    $heldPaidAmount = (float) ($heldBill['paid_amount'] ?? 0);
                    $heldTotalAmount = (float) ($heldBill['total_price'] ?? 0);
                    $heldBalanceAmount = max(0.0, $heldTotalAmount - $heldPaidAmount);
                    $heldBillLabel = (string) (($heldBill['bill_number'] ?? '') !== '' ? $heldBill['bill_number'] : '#' . $heldBillId);
                    $isCurrentBill = $editingOrder && (int) ($editingOrder['order_id'] ?? 0) === $heldBillId;
                    ?>
                    <tr<?= $isCurrentBill ? ' class="is-current"' : '' ?>>
                        <td>
                            <strong><?= e($heldBillLabel) ?></strong>
                            <span class="muted"><?= e(format_datetime((string) ($heldBill['order_date'] ?? ''))) ?></span>
                        </td>
                        <td><?= e((string) ($heldBill['branch_name'] ?? '-')) ?></td>
                        <td>
                            <strong><?= e(strtr($itemCountLabel, array('{count}' => (string) (int) ($heldBill['item_count'] ?? 0)))) ?></strong>
                            <span class="muted"><?= e((string) ($heldBill['service_names'] ?? '-')) ?></span>
                        </td>
                        <td class="number"><?= format_money($heldTotalAmount) ?></td>
                        <td class="number"><?= format_money($heldPaidAmount) ?></td>
                        <td class="number"><?= format_money($heldBalanceAmount) ?></td>
                        <td>
                            <span class="<?= e(payment_status_class((string) ($heldBill['payment_status'] ?? 'unpaid'))) ?>">
                                <?= e(payment_status_label((string) ($heldBill['payment_status'] ?? 'unpaid'))) ?>
                            </span>
                        </td>
                        <td><?= e(format_datetime((string) ($heldBill['updated_at'] ?? ''))) ?></td>
                        <td>
                            <div class="inline-actions">
                                <a class="button button-secondary" href="quick_service.php?id=<?= $heldBillId ?>"><?= e($resumeLabel) ?></a>
                                <?php if ($canCancelHeldBill): ?>
                                    <a class="button button-danger" href="cancel_bill.php?id=<?= $heldBillId ?>&return_to=<?= e(urlencode('quick_service.php')) ?>"><?= e($cancelBillLabel) ?></a>
                                <?php endif; ?>
                            </div>
                        </td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
    </section>
<?php endif; ?>

<?php render_page_end(); ?>
