<?php
declare(strict_types=1);

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

require_permission($conn, 'queue');

ensure_order_branch_column($conn);
ensure_order_return_column($conn);
ensure_order_slide_send_column($conn);
ensure_order_service_at_column($conn);
ensure_order_bill_number_column($conn);
ensure_order_cancellation_columns($conn);
ensure_order_reopen_column($conn);
ensure_order_source_column($conn);
ensure_car_profile_columns($conn);

$canControlBill = can_access($conn, 'queue_bill_control');
$canCancelClosedBill = can_access($conn, 'queue_cancel_closed');
$canCancelOpenBill = can_access($conn, 'queue_cancel_open');
$canReceiveQueuePayment = can_access($conn, 'queue_payment');
$canStartWaiting = can_access($conn, 'queue_start_waiting');
$canCancelWaiting = can_access($conn, 'queue_cancel_waiting');

$allowedStatuses = array('waiting', 'washing', 'done');
if ($canControlBill) {
    $allowedStatuses[] = 'cancelled';
}

$status = (string) ($_GET['status'] ?? 'waiting');
if (!in_array($status, $allowedStatuses, true)) {
    $status = 'waiting';
}

$allowedSources = array('all', 'booking', 'quick_service');
$sourceFilter = (string) ($_GET['source'] ?? 'all');
if (!in_array($sourceFilter, $allowedSources, true)) {
    $sourceFilter = 'all';
}

$searchQuery = trim((string) ($_GET['q'] ?? ''));
$allowedSorts = array('queue', 'latest', 'oldest');
$sort = (string) ($_GET['sort'] ?? 'queue');
if (!in_array($sort, $allowedSorts, true)) {
    $sort = 'queue';
}

$queueReturnTo = 'queue.php?status=' . urlencode($status);
if ($sourceFilter !== 'all') {
    $queueReturnTo .= '&source=' . urlencode($sourceFilter);
}
if ($searchQuery !== '') {
    $queueReturnTo .= '&q=' . urlencode($searchQuery);
}
if ($sort !== 'queue') {
    $queueReturnTo .= '&sort=' . urlencode($sort);
}

$queueBuildUrl = static function (string $targetStatus, string $targetSource, string $targetSearch, string $targetSort): string {
    $query = array('status' => $targetStatus);
    if ($targetSource !== 'all') {
        $query['source'] = $targetSource;
    }
    if ($targetSearch !== '') {
        $query['q'] = $targetSearch;
    }
    if ($targetSort !== 'queue') {
        $query['sort'] = $targetSort;
    }

    return 'queue.php?' . http_build_query($query);
};

$jobs = array();
$types = 's';
$params = array($status);
$where = array('o.status = ?');

if ($sourceFilter !== 'all') {
    $where[] = 'o.order_source = ?';
    $types .= 's';
    $params[] = $sourceFilter;
}

if ($status === 'done') {
    // Hide fully paid completed jobs after the payment day ends, but keep unpaid ones visible.
    $where[] = "(o.payment_status <> 'paid' OR DATE(COALESCE(payment_summary.last_payment_at, o.finished_at, o.order_date)) = CURDATE())";
} elseif ($status === 'cancelled') {
    // Hide cancelled jobs after the cancellation day ends.
    $where[] = "DATE(COALESCE(o.cancelled_at, o.order_date)) = CURDATE()";
}

if ($searchQuery !== '') {
    $searchLike = '%' . $searchQuery . '%';
    $where[] = "(o.bill_number LIKE ?
        OR c.name LIKE ?
        OR c.phone LIKE ?
        OR car.plate_number LIKE ?
        OR car.brand LIKE ?
        OR car.model LIKE ?
        OR COALESCE(services.service_names, '') LIKE ?)";
    $types .= str_repeat('s', 7);
    $params[] = $searchLike;
    $params[] = $searchLike;
    $params[] = $searchLike;
    $params[] = $searchLike;
    $params[] = $searchLike;
    $params[] = $searchLike;
    $params[] = $searchLike;
}

$branchCondition = auth_branch_condition($conn, 'o', $types, $params);
if ($branchCondition !== '') {
    $where[] = $branchCondition;
}

$orderBySql = 'ORDER BY COALESCE(q.queue_number, 999999) ASC, COALESCE(q.created_at, o.order_date) ASC, o.order_id ASC';
if ($sort === 'latest') {
    $orderBySql = 'ORDER BY COALESCE(q.created_at, o.order_date) DESC, o.order_id DESC';
} elseif ($sort === 'oldest') {
    $orderBySql = 'ORDER BY COALESCE(q.created_at, o.order_date) ASC, o.order_id ASC';
}

$whereSql = implode(' AND ', $where);
$stmt = db_prepare($conn, "
    SELECT
        o.order_id,
        o.bill_number,
        o.order_date,
        o.branch_name,
        o.scheduled_at,
        o.slide_send_at,
        o.service_at,
        o.return_at,
        o.started_at,
        o.finished_at,
        o.status,
        o.payment_status,
        o.order_source,
        o.total_price,
        o.reopened_from_order_id,
        reopened.bill_number AS reopened_from_bill_number,
        c.name AS customer_name,
        c.phone,
        car.plate_number,
        car.province,
        car.brand,
        car.model,
        car.profile_image_path,
        car.profile_image_name,
        q.queue_number,
        q.created_at AS queued_at,
        services.service_names,
        payment_summary.last_payment_at
    FROM orders o
    LEFT JOIN orders reopened ON reopened.order_id = o.reopened_from_order_id
    INNER JOIN customers c ON c.customer_id = o.customer_id
    INNER JOIN cars car ON car.car_id = o.car_id
    LEFT JOIN queue q ON q.order_id = o.order_id
    LEFT JOIN (
        SELECT
            p.order_id,
            MAX(p.payment_date) AS last_payment_at
        FROM payments p
        GROUP BY p.order_id
    ) payment_summary ON payment_summary.order_id = o.order_id
    LEFT JOIN (
        SELECT
            od.order_id,
            GROUP_CONCAT(od.service_name_snapshot ORDER BY od.detail_id SEPARATOR ', ') AS service_names
        FROM order_details od
        GROUP BY od.order_id
    ) services ON services.order_id = o.order_id
    WHERE {$whereSql}
    {$orderBySql}
");
$stmt->bind_param($types, ...$params);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    $jobs[] = $row;
}
$stmt->close();

$statusCountMap = array(
    'waiting' => 0,
    'washing' => 0,
    'done' => 0,
    'cancelled' => 0,
);

$countTypes = '';
$countParams = array();
$countWhere = array(
    "(
        o.status IN ('waiting', 'washing')
        OR (o.status = 'done' AND (o.payment_status <> 'paid' OR DATE(COALESCE(payment_summary.last_payment_at, o.finished_at, o.order_date)) = CURDATE()))
        OR (o.status = 'cancelled' AND DATE(COALESCE(o.cancelled_at, o.order_date)) = CURDATE())
    )",
);

if ($sourceFilter !== 'all') {
    $countWhere[] = 'o.order_source = ?';
    $countTypes .= 's';
    $countParams[] = $sourceFilter;
}

$countBranchCondition = auth_branch_condition($conn, 'o', $countTypes, $countParams);
if ($countBranchCondition !== '') {
    $countWhere[] = $countBranchCondition;
}

$countWhereSql = implode(' AND ', $countWhere);
$countStmt = db_prepare($conn, "
    SELECT
        o.status,
        COUNT(*) AS total
    FROM orders o
    LEFT JOIN (
        SELECT
            p.order_id,
            MAX(p.payment_date) AS last_payment_at
        FROM payments p
        GROUP BY p.order_id
    ) payment_summary ON payment_summary.order_id = o.order_id
    WHERE {$countWhereSql}
    GROUP BY o.status
");

if ($countTypes !== '') {
    $countStmt->bind_param($countTypes, ...$countParams);
}

$countStmt->execute();
$countResult = $countStmt->get_result();
while ($countRow = $countResult->fetch_assoc()) {
    $countStatus = (string) ($countRow['status'] ?? '');
    if (array_key_exists($countStatus, $statusCountMap)) {
        $statusCountMap[$countStatus] = (int) ($countRow['total'] ?? 0);
    }
}
$countStmt->close();

$renderStatusAction = static function (
    int $orderId,
    string $nextStatus,
    string $label,
    string $buttonClass,
    string $icon,
    string $returnTo
): string {
    $submissionScope = 'queue_status_' . $orderId . '_' . $nextStatus;

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

$pageTitle = localized_text_value('คิวงาน', 'Queue');
$pageHeroTitle = localized_text_value('คิวบริการ', 'Service queue');
$pageHeroDescription = localized_text_value(
    'เปลี่ยนสถานะรถจากรอดำเนินการเป็นกำลังให้บริการ และปิดงานเมื่อเสร็จสิ้น',
    'Move vehicles from waiting to in service, then close completed jobs.'
);
$newBookingLabel = localized_text_value('เปิดงานใหม่', 'New booking');
$quickServiceLabel = localized_text_value('ควิกเซอร์วิส', 'Quick service');
$queueFiltersLabel = localized_text_value('ตัวกรองคิวงาน', 'Queue filters');
$billNumberLabel = localized_text_value('เลขที่บิล', 'Bill no.');
$referenceLabel = localized_text_value('อ้างอิง', 'Ref.');
$vehiclePendingLabel = localized_text_value('ยังไม่มีรายละเอียดรถ', 'Vehicle details pending');
$noJobsMessage = localized_text_value('ไม่มีงานในสถานะ {status}', 'No jobs in {status}.');
$noSearchJobsMessage = localized_text_value('ไม่พบข้อมูลที่ค้นหาในสถานะ {status}', 'No matching jobs found in {status}.');
$searchLabel = localized_text_value('ค้นหาคิวงาน', 'Search queue');
$searchPlaceholder = localized_text_value('ค้นหาทะเบียนรถ, ลูกค้า, เบอร์โทร, ยี่ห้อ, รุ่น', 'Search plate, customer, phone, brand, model');
$searchButtonLabel = localized_text_value('ค้นหารายการ', 'Search');
$clearSearchLabel = localized_text_value('ล้างคำค้น', 'Clear');
$sortLabel = localized_text_value('เรียง', 'Sort');
$sortQueueLabel = localized_text_value('ตามคิว', 'Queue order');
$sortLatestLabel = localized_text_value('ล่าสุด', 'Latest');
$sortOldestLabel = localized_text_value('เก่าสุด', 'Oldest');
$sourceFilterLabel = localized_text_value('ประเภทบิล', 'Bill type');
$allSourcesLabel = localized_text_value('ทั้งหมด', 'All');
$bookingSourceLabel = localized_text_value('Booking', 'Booking');
$quickServiceSourceLabel = localized_text_value('Quick Service', 'Quick Service');
$searchResultSummary = localized_text_value('ผลการค้นหา {count} รายการ', '{count} matching jobs');
$openedAtLabel = ui_text('เปิดงาน', 'Opened');
$scheduleAtLabel = ui_text('นัดหมาย', 'Schedule');

$statusRetentionMessage = '';
if ($status === 'done') {
    $statusRetentionMessage = localized_text_value(
        'แสดงเฉพาะงานเสร็จสิ้นที่ยังค้างชำระ หรือชำระครบภายในวันนี้',
        'Only completed jobs that are still unpaid/partial, or fully paid today, are shown here.'
    );
} elseif ($status === 'cancelled') {
    $statusRetentionMessage = localized_text_value(
        'แสดงเฉพาะงานที่ยกเลิกภายในวันนี้',
        'Only jobs cancelled today are shown here.'
    );
}

$queueCountSummary = strtr(
    localized_text_value('{count} งานสถานะ {status}', '{count} job(s) in {status}'),
    array(
        '{count}' => (string) count($jobs),
        '{status}' => status_label($status),
    )
);

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

<section class="page-hero queue-hero">
    <div>
        <h1><?= e($pageHeroTitle) ?></h1>
        <p><?= e($pageHeroDescription) ?></p>
    </div>
</section>

<section class="card queue-control-card">
    <div class="queue-control-main">
        <nav class="tabs queue-tabs" aria-label="<?= e($queueFiltersLabel) ?>">
            <?php foreach ($allowedStatuses as $tabStatus): ?>
                <?php
                $tabCount = (int) ($statusCountMap[$tabStatus] ?? 0);
                $tabHref = $queueBuildUrl($tabStatus, $sourceFilter, $searchQuery, $sort);
                ?>
                <a class="<?= $status === $tabStatus ? 'is-active' : '' ?>" href="<?= e($tabHref) ?>">
                    <span><?= e(status_label($tabStatus)) ?></span>
                    <span class="queue-tab-count"><?= $tabCount ?></span>
                </a>
            <?php endforeach; ?>
        </nav>

        <nav class="queue-source-filter" aria-label="<?= e($sourceFilterLabel) ?>">
            <?php
            $sourceTabs = array(
                'all' => $allSourcesLabel,
                'booking' => $bookingSourceLabel,
                'quick_service' => $quickServiceSourceLabel,
            );
            ?>
            <?php foreach ($sourceTabs as $sourceValue => $sourceLabel): ?>
                <a class="<?= $sourceFilter === $sourceValue ? 'is-active' : '' ?>" href="<?= e($queueBuildUrl($status, (string) $sourceValue, $searchQuery, $sort)) ?>">
                    <?= e((string) $sourceLabel) ?>
                </a>
            <?php endforeach; ?>
        </nav>

        <form class="queue-search-form" method="GET" action="queue.php">
            <input type="hidden" name="status" value="<?= e($status) ?>">
            <input type="hidden" name="source" value="<?= e($sourceFilter) ?>">
            <label class="queue-search-field" for="queue-search-input">
                <span class="queue-search-icon" aria-hidden="true"><?= app_button_icon_svg('search') ?></span>
                <input
                    id="queue-search-input"
                    type="search"
                    name="q"
                    value="<?= e($searchQuery) ?>"
                    placeholder="<?= e($searchPlaceholder) ?>"
                    aria-label="<?= e($searchLabel) ?>"
                >
            </label>
            <label class="queue-sort-field">
                <span><?= e($sortLabel) ?></span>
                <select name="sort" aria-label="<?= e($sortLabel) ?>">
                    <option value="queue"<?= $sort === 'queue' ? ' selected' : '' ?>><?= e($sortQueueLabel) ?></option>
                    <option value="latest"<?= $sort === 'latest' ? ' selected' : '' ?>><?= e($sortLatestLabel) ?></option>
                    <option value="oldest"<?= $sort === 'oldest' ? ' selected' : '' ?>><?= e($sortOldestLabel) ?></option>
                </select>
            </label>
            <button class="button button-secondary app-action-button" type="submit">
                <?= app_button_content('search', $searchButtonLabel) ?>
            </button>
            <?php if ($searchQuery !== ''): ?>
                <a class="button button-ghost app-action-button" href="<?= e($queueBuildUrl($status, $sourceFilter, '', $sort)) ?>">
                    <?= app_button_content('rotate-ccw', $clearSearchLabel) ?>
                </a>
            <?php endif; ?>
        </form>

        <div class="actions queue-toolbar-actions">
            <a class="button button-accent app-action-button" href="booking.php">
                <?= app_button_content('plus-square', $newBookingLabel) ?>
            </a>
            <?php if (can_access($conn, 'quick_service')): ?>
                <a class="button button-secondary app-action-button" href="quick_service.php">
                    <?= app_button_content('wrench', $quickServiceLabel) ?>
                </a>
            <?php endif; ?>
        </div>
    </div>

    <div class="queue-toolbar-copy">
        <strong><?= e($queueCountSummary) ?></strong>
        <?php if ($searchQuery !== ''): ?>
            <span><?= e(strtr($searchResultSummary, array('{count}' => (string) count($jobs)))) ?></span>
        <?php elseif ($statusRetentionMessage !== ''): ?>
            <span><?= e($statusRetentionMessage) ?></span>
        <?php endif; ?>
    </div>
</section>

<?php if (empty($jobs)): ?>
    <section class="empty-state">
        <?php if ($searchQuery !== ''): ?>
            <?= e(strtr($noSearchJobsMessage, array('{status}' => status_label($status)))) ?>
        <?php else: ?>
            <?= e(strtr($noJobsMessage, array('{status}' => status_label($status)))) ?>
        <?php endif; ?>
    </section>
<?php else: ?>
    <section class="grid queue-grid">
        <?php foreach ($jobs as $job): ?>
            <?php
            $brandModel = trim((string) (($job['brand'] ?? '') . ' ' . ($job['model'] ?? '')));
            $queueNumber = (int) ($job['queue_number'] ?? 0);
            $reopenedFromOrderId = (int) ($job['reopened_from_order_id'] ?? 0);
            $reopenedFromBillNumber = (string) ($job['reopened_from_bill_number'] ?? '');
            $reopenedFromLabel = $reopenedFromOrderId > 0 ? ($reopenedFromBillNumber !== '' ? $reopenedFromBillNumber : '#' . $reopenedFromOrderId) : '';
            $jobStatus = (string) $job['status'];
            $paymentStatus = (string) ($job['payment_status'] ?? 'unpaid');
            $jobIsClosed = $jobStatus === 'done' || $paymentStatus === 'paid';
            $isFullyPaid = $paymentStatus === 'paid';
            $jobDetailsHref = 'job_details.php?id=' . (int) $job['order_id'];
            $jobPaymentHref = $jobDetailsHref . '#payment-section';
            $canCancelJob = $jobStatus !== 'cancelled' && (
                ($jobStatus === 'waiting' && $canCancelWaiting)
                || ($jobStatus !== 'waiting' && $jobIsClosed && $canCancelClosedBill)
                || ($jobStatus !== 'waiting' && !$jobIsClosed && $canCancelOpenBill)
            );

            $queuedAt = format_datetime($job['queued_at'] ? (string) $job['queued_at'] : (string) ($job['order_date'] ?? ''));
            $slidePickupAt = format_datetime($job['scheduled_at'] ? (string) $job['scheduled_at'] : null);
            $serviceAt = format_datetime($job['service_at'] ? (string) $job['service_at'] : null);
            $pickupAt = format_datetime($job['return_at'] ? (string) $job['return_at'] : null);
            $scheduleAt = $slidePickupAt !== '-' ? $slidePickupAt : ($serviceAt !== '-' ? $serviceAt : $pickupAt);
            $phone = trim((string) ($job['phone'] ?? ''));
            $branch = trim((string) ($job['branch_name'] ?? ''));
            $orderSource = (string) ($job['order_source'] ?? 'booking');
            $sourceLabel = $orderSource === 'quick_service' ? $quickServiceSourceLabel : $bookingSourceLabel;
            $sourceClass = $orderSource === 'quick_service' ? 'is-quick-service' : 'is-booking';
            ?>
            <article class="job-card queue-card queue-card-v4 queue-card--status-<?= e($jobStatus) ?>">
                <div class="queue-card-v4-head">
                    <span class="queue-chip queue-card-v4-number"><?= $queueNumber > 0 ? '#' . $queueNumber : '-' ?></span>
                    <div class="queue-card-bill-row">
                        <span class="queue-card-bill-label"><?= e($billNumberLabel) ?>:</span>
                        <strong class="queue-card-bill-value"><?= e((string) ($job['bill_number'] ?: '#' . (int) $job['order_id'])) ?></strong>
                    </div>
                    <div class="queue-card-status">
                        <span class="queue-source-badge <?= e($sourceClass) ?>"><?= e($sourceLabel) ?></span>
                        <span class="<?= e(status_class($jobStatus)) ?>"><?= e(status_label($jobStatus)) ?></span>
                        <span class="<?= e(payment_status_class($paymentStatus)) ?>"><?= e(payment_status_label($paymentStatus)) ?></span>
                    </div>
                </div>

                <div class="queue-card-v4-body">
                    <div class="queue-card-v4-plate-col">
                        <span class="plate-card queue-card-plate">
                            <span class="plate"><?= e((string) $job['plate_number']) ?></span>
                            <?php if (trim((string) ($job['province'] ?? '')) !== ''): ?>
                                <span class="plate-province"><?= e(translate_text((string) $job['province'])) ?></span>
                            <?php endif; ?>
                        </span>
                        <?php if ($branch !== ''): ?>
                            <span class="queue-card-branch"><?= e($branch) ?></span>
                        <?php endif; ?>
                    </div>

                    <div class="queue-card-v4-main">
                        <div class="queue-card-title">
                            <strong class="queue-card-customer"><?= e((string) $job['customer_name']) ?></strong>
                            <span class="queue-card-vehicle"><?= e($brandModel !== '' ? $brandModel : $vehiclePendingLabel) ?></span>
                        </div>
                        <span class="queue-card-services"><?= e((string) ($job['service_names'] ?? '-')) ?></span>
                        <?php if ($phone !== ''): ?>
                            <span class="queue-card-phone"><?= e($phone) ?></span>
                        <?php endif; ?>
                        <?php if ($reopenedFromLabel !== ''): ?>
                            <span class="queue-card-reference muted"><?= e($referenceLabel) ?> <?= e($reopenedFromLabel) ?></span>
                        <?php endif; ?>
                        <div class="queue-card-v4-meta">
                            <span><?= e($openedAtLabel) ?>: <?= e($queuedAt) ?></span>
                            <?php if ($scheduleAt !== '-'): ?>
                                <span><?= e($scheduleAtLabel) ?>: <?= e($scheduleAt) ?></span>
                            <?php endif; ?>
                        </div>
                    </div>

                    <div class="queue-card-v4-photo-col">
                        <?= car_profile_photo_html($job, 'vehicle-profile-photo vehicle-profile-photo--lg queue-card-photo-lg', 'vehicle-profile-photo-placeholder vehicle-profile-photo-placeholder--lg queue-card-photo-lg queue-card-photo-placeholder-lg') ?>
                    </div>
                </div>

                <div class="queue-card-v4-actions">
                    <div class="actions queue-secondary-actions queue-secondary-actions--info">
                        <a class="button button-secondary queue-details-button app-action-button" href="<?= e($jobDetailsHref) ?>" aria-label="<?= e(ui_text('รายละเอียด', 'Details')) ?>" title="<?= e(ui_text('รายละเอียด', 'Details')) ?>">
                            <?= app_button_content('eye', ui_text('รายละเอียด', 'Details')) ?>
                        </a>
                        <?php if ($status === 'done' && $canReceiveQueuePayment): ?>
                            <?php if ($isFullyPaid): ?>
                                <span class="button button-secondary queue-details-button is-disabled app-action-button" aria-disabled="true" aria-label="<?= e(ui_text('ชำระเงิน', 'Payment')) ?>" title="<?= e(ui_text('ชำระเงิน', 'Payment')) ?>">
                                    <?= app_button_content('wallet', ui_text('ชำระเงิน', 'Payment')) ?>
                                </span>
                            <?php else: ?>
                                <a class="button button-accent queue-details-button app-action-button" href="<?= e($jobPaymentHref) ?>" aria-label="<?= e(ui_text('ชำระเงิน', 'Payment')) ?>" title="<?= e(ui_text('ชำระเงิน', 'Payment')) ?>">
                                    <?= app_button_content('wallet', ui_text('ชำระเงิน', 'Payment')) ?>
                                </a>
                            <?php endif; ?>
                        <?php endif; ?>
                    </div>

                    <div class="actions queue-secondary-actions queue-secondary-actions--main">
                        <?php if ($status === 'waiting' && $canStartWaiting): ?>
                            <?= $renderStatusAction((int) $job['order_id'], 'washing', ui_text('เริ่มงาน', 'Start'), 'button app-action-button', 'play', $queueReturnTo) ?>
                        <?php elseif ($status === 'washing'): ?>
                            <?php if ($canControlBill): ?>
                                <?= $renderStatusAction((int) $job['order_id'], 'waiting', ui_text('ย้อนกลับ', 'Back'), 'button button-secondary app-action-button', 'arrow-left', $queueReturnTo) ?>
                            <?php endif; ?>
                            <?= $renderStatusAction((int) $job['order_id'], 'done', ui_text('เสร็จสิ้น', 'Complete'), 'button button-accent app-action-button', 'check', $queueReturnTo) ?>
                        <?php elseif ($status === 'done' && $canControlBill): ?>
                            <?= $renderStatusAction((int) $job['order_id'], 'washing', ui_text('ย้อนกลับ', 'Back'), 'button button-secondary app-action-button', 'arrow-left', $queueReturnTo) ?>
                        <?php elseif ($status === 'cancelled' && $canControlBill): ?>
                            <?= $renderStatusAction((int) $job['order_id'], 'waiting', ui_text('เปิดใหม่', 'Reopen'), 'button button-secondary app-action-button', 'refresh-cw', $queueReturnTo) ?>
                        <?php endif; ?>

                        <?php if ($canCancelJob): ?>
                            <a class="button button-danger app-action-button" href="cancel_bill.php?id=<?= (int) $job['order_id'] ?>&return_to=<?= e(urlencode($queueReturnTo)) ?>" aria-label="<?= e(ui_text('ยกเลิก', 'Cancel')) ?>" title="<?= e(ui_text('ยกเลิก', 'Cancel')) ?>">
                                <?= app_button_content('x', ui_text('ยกเลิก', 'Cancel')) ?>
                            </a>
                        <?php endif; ?>
                    </div>
                </div>
            </article>
        <?php endforeach; ?>
    </section>
<?php endif; ?>

<?php render_page_end(); ?>
