<?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);

$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';
}
$queueReturnTo = 'queue.php?status=' . urlencode($status);

$jobs = array();
$types = 's';
$params = array($status);
$where = array('o.status = ?', "o.order_source = 'booking'");
$branchCondition = auth_branch_condition($conn, 'o', $types, $params);
if ($branchCondition !== '') {
    $where[] = $branchCondition;
}
$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.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,
        q.queue_number,
        q.created_at AS queued_at,
        services.service_names
    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
            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}
    ORDER BY q.queue_number ASC, o.order_id ASC
");
$stmt->bind_param($types, ...$params);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    $jobs[] = $row;
}
$stmt->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">'
        . 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}.');

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

<section class="page-hero">
    <div>
        <h1><?= e($pageHeroTitle) ?></h1>
        <p><?= e($pageHeroDescription) ?></p>
    </div>
    <div class="hero-actions">
        <a class="button button-accent" href="booking.php"><?= e($newBookingLabel) ?></a>
        <?php if (can_access($conn, 'quick_service')): ?>
            <a class="button button-secondary" href="quick_service.php"><?= e($quickServiceLabel) ?></a>
        <?php endif; ?>
    </div>
</section>

<nav class="tabs" aria-label="<?= e($queueFiltersLabel) ?>">
    <?php foreach ($allowedStatuses as $tabStatus): ?>
        <a class="<?= $status === $tabStatus ? 'is-active' : '' ?>" href="queue.php?status=<?= e($tabStatus) ?>">
            <?= e(status_label($tabStatus)) ?>
        </a>
    <?php endforeach; ?>
</nav>

<?php if (empty($jobs)): ?>
    <section class="empty-state">
        <?= e(strtr($noJobsMessage, array('{status}' => status_label($status)))) ?>
    </section>
<?php else: ?>
    <section class="grid grid-2 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' || (string) $job['payment_status'] === 'paid';
            $isFullyPaid = $paymentStatus === 'paid';
            $canCancelJob = $jobStatus !== 'cancelled' && (
                ($jobStatus === 'waiting' && $canCancelWaiting)
                || ($jobStatus !== 'waiting' && $jobIsClosed && $canCancelClosedBill)
                || ($jobStatus !== 'waiting' && !$jobIsClosed && $canCancelOpenBill)
            );
            ?>
            <article class="job-card queue-card">
                <div class="queue-card-identity">
                    <span class="queue-chip"><?= $queueNumber > 0 ? '#' . $queueNumber : '-' ?></span>
                    <span class="plate-card">
                        <span class="plate"><?= e((string) $job['plate_number']) ?></span>
                        <?php if (trim((string) ($job['province'] ?? '')) !== ''): ?>
                            <span class="plate-province"><?= e((string) $job['province']) ?></span>
                        <?php endif; ?>
                    </span>
                </div>

                <div class="queue-card-main">
                    <span class="muted"><?= e($billNumberLabel) ?>: <?= e((string) ($job['bill_number'] ?: '#' . (int) $job['order_id'])) ?></span>
                    <?php if ($reopenedFromLabel !== ''): ?>
                        <span class="muted"><?= e($referenceLabel) ?> <?= e($reopenedFromLabel) ?></span>
                    <?php endif; ?>
                    <div class="queue-card-title">
                        <strong><?= e((string) $job['customer_name']) ?></strong>
                        <span><?= e($brandModel !== '' ? $brandModel : $vehiclePendingLabel) ?></span>
                    </div>
                    <span><?= e((string) ($job['service_names'] ?? '-')) ?></span>
                    <span class="muted"><?= e(ui_text('วันสไลด์รับ', 'Slide pickup')) ?>: <?= e(format_datetime($job['scheduled_at'] ? (string) $job['scheduled_at'] : null)) ?></span>
                    <span class="muted"><?= e(ui_text('วันสไลด์ส่ง', 'Slide delivery')) ?>: <?= e(format_datetime($job['slide_send_at'] ? (string) $job['slide_send_at'] : null)) ?></span>
                    <span class="muted"><?= e(ui_text('วันเข้าใช้บริการ', 'Service date')) ?>: <?= e(format_datetime($job['service_at'] ? (string) $job['service_at'] : null)) ?></span>
                    <span class="muted"><?= e(ui_text('วันรับรถ', 'Pickup date')) ?>: <?= e(format_datetime($job['return_at'] ? (string) $job['return_at'] : null)) ?></span>
                </div>

                <div class="queue-card-side">
                    <div class="queue-card-status">
                        <span class="<?= e(status_class((string) $job['status'])) ?>"><?= e(status_label((string) $job['status'])) ?></span>
                        <span class="<?= e(payment_status_class($paymentStatus)) ?>"><?= e(payment_status_label($paymentStatus)) ?></span>
                    </div>
                    <?php if ($status === 'done'): ?>
                        <?php if (!$canReceiveQueuePayment): ?>
                            <a class="button button-secondary queue-details-button app-action-button" href="job_details.php?id=<?= (int) $job['order_id'] ?>"><?= app_button_content('eye', ui_text('รายละเอียด', 'Details')) ?></a>
                        <?php elseif ($isFullyPaid): ?>
                            <span class="button button-secondary queue-details-button is-disabled app-action-button" aria-disabled="true"><?= app_button_content('wallet', ui_text('ชำระเงิน', 'Payment')) ?></span>
                        <?php else: ?>
                            <a class="button button-accent queue-details-button app-action-button" href="job_details.php?id=<?= (int) $job['order_id'] ?>#payment-section"><?= app_button_content('wallet', ui_text('ชำระเงิน', 'Payment')) ?></a>
                        <?php endif; ?>
                    <?php else: ?>
                        <a class="button button-secondary queue-details-button app-action-button" href="job_details.php?id=<?= (int) $job['order_id'] ?>"><?= app_button_content('eye', ui_text('รายละเอียด', 'Details')) ?></a>
                    <?php endif; ?>
                    <div class="actions queue-secondary-actions">
                        <?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-secondary app-action-button" href="cancel_bill.php?id=<?= (int) $job['order_id'] ?>&return_to=<?= e(urlencode($queueReturnTo)) ?>"><?= app_button_content('x', ui_text('ยกเลิก', 'Cancel')) ?></a>
                        <?php endif; ?>
                    </div>
                </div>
            </article>
        <?php endforeach; ?>
    </section>
<?php endif; ?>

<?php render_page_end(); ?>
