<?php
declare(strict_types=1);

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

require_login($conn);

ensure_order_branch_column($conn);
ensure_order_bill_number_column($conn);
ensure_order_cancellation_columns($conn);
ensure_order_source_column($conn);

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

$returnTo = safe_page_return((string) ($_GET['return_to'] ?? ''), '');

$stmt = db_prepare($conn, "
    SELECT
        o.order_id,
        o.bill_number,
        o.order_date,
        o.branch_name,
        o.order_source,
        o.status,
        o.payment_status,
        o.total_price,
        c.name AS customer_name,
        car.plate_number,
        car.brand,
        car.model
    FROM orders o
    INNER JOIN customers c ON c.customer_id = o.customer_id
    INNER JOIN cars car ON car.car_id = o.car_id
    WHERE o.order_id = ?
    LIMIT 1
");
$stmt->bind_param('i', $orderId);
$stmt->execute();
$job = $stmt->get_result()->fetch_assoc();
$stmt->close();

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

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

if ((string) $job['status'] === 'cancelled') {
    $defaultReturnPath = (string) ($job['order_source'] ?? 'booking') === 'quick_service'
        ? 'quick_service.php'
        : 'job_details.php?id=' . $orderId;
    redirect_with_flash($returnTo !== '' ? $returnTo : $defaultReturnPath, 'error', localized_flash_message('บิลนี้ถูกยกเลิกแล้ว', 'This bill is already cancelled.'));
}

$isBillClosed = (string) $job['status'] === 'done' || (string) $job['payment_status'] === 'paid';
$isQuickServiceBill = (string) ($job['order_source'] ?? 'booking') === 'quick_service';
$isWaitingQueueBill = !$isQuickServiceBill && (string) $job['status'] === 'waiting';
$canCancelBill = ($isBillClosed && !$isWaitingQueueBill && can_access($conn, 'queue_cancel_closed'))
    || ($isWaitingQueueBill && can_access($conn, 'queue_cancel_waiting'))
    || (!$isBillClosed && !$isWaitingQueueBill && (can_access($conn, 'queue_cancel_open') || ($isQuickServiceBill && can_access($conn, 'quick_service'))));

if (!$canCancelBill) {
    $defaultReturnPath = (string) ($job['order_source'] ?? 'booking') === 'quick_service'
        ? 'quick_service.php'
        : 'job_details.php?id=' . $orderId;
    redirect_with_flash($returnTo !== '' ? $returnTo : $defaultReturnPath, 'error', localized_flash_message('คุณไม่มีสิทธิ์ยกเลิกบิลนี้', 'You do not have permission to cancel this bill.'));
}

$brandModel = trim((string) (($job['brand'] ?? '') . ' ' . ($job['model'] ?? '')));
$billNumber = (string) ($job['bill_number'] ?? '');
$billLabel = $billNumber !== '' ? $billNumber : '#' . (int) $job['order_id'];

$activePage = $isQuickServiceBill ? 'quick_service' : 'queue';
$defaultReturnPath = $isQuickServiceBill
    ? 'quick_service.php'
    : 'job_details.php?id=' . (int) $job['order_id'];

$pageTitle = $isQuickServiceBill
    ? localized_text_value('ยกเลิกบิลควิกเซอร์วิส', 'Cancel Quick Service Bill')
    : localized_text_value('ยกเลิกบิล', 'Cancel Bill');
$pageDescription = $isQuickServiceBill
    ? localized_text_value('บันทึกเหตุผลก่อนยกเลิกบิลพักนี้ รวมถึงรายการชำระเงินที่บันทึกไว้แล้ว', 'Record the cancellation reason before cancelling this held bill together with any payment already recorded on it.')
    : localized_text_value('บันทึกเหตุผลก่อนยกเลิกบิลนี้', 'Record the cancellation reason before voiding this bill.');

$backLabel = localized_text_value('กลับ', 'Back');
$billSummaryLabel = localized_text_value('สรุปบิล', 'Bill summary');
$customerLabel = localized_text_value('ลูกค้า', 'Customer');
$plateNumberLabel = localized_text_value('ทะเบียนรถ', 'Plate number');
$vehicleLabel = localized_text_value('รถ', 'Vehicle');
$totalLabel = localized_text_value('รวมทั้งสิ้น', 'Total');
$cancelReasonLabel = localized_text_value('เหตุผลในการยกเลิก', 'Cancel reason');
$reasonFieldLabel = localized_text_value('เหตุผล', 'Reason');
$confirmCancelLabel = localized_text_value('ยืนยันยกเลิกบิล', 'Confirm cancel bill');
$keepBillLabel = localized_text_value('คงบิลนี้ไว้', 'Keep bill');

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

<section class="page-hero">
    <div>
        <h1><?= e($pageTitle) ?> <?= e($billLabel) ?></h1>
        <p><?= e($pageDescription) ?></p>
    </div>
    <div class="hero-actions">
        <a class="button button-secondary" href="<?= e($returnTo !== '' ? $returnTo : $defaultReturnPath) ?>"><?= e($backLabel) ?></a>
    </div>
</section>

<div class="content-grid">
    <section class="card">
        <h2 class="section-title"><?= e($billSummaryLabel) ?></h2>
        <div class="grid grid-2" style="margin-top: 18px;">
            <div class="stack">
                <span class="muted"><?= e($customerLabel) ?></span>
                <strong><?= e((string) $job['customer_name']) ?></strong>
            </div>
            <div class="stack">
                <span class="muted"><?= e($plateNumberLabel) ?></span>
                <strong><?= e((string) $job['plate_number']) ?></strong>
            </div>
            <div class="stack">
                <span class="muted"><?= e($vehicleLabel) ?></span>
                <strong><?= e($brandModel !== '' ? $brandModel : '-') ?></strong>
            </div>
            <div class="stack">
                <span class="muted"><?= e($totalLabel) ?></span>
                <strong><?= format_money($job['total_price']) ?> THB</strong>
            </div>
        </div>
    </section>

    <section class="form-card">
        <h2 class="section-title"><?= e($cancelReasonLabel) ?></h2>
        <form method="POST" action="../process/cancel_bill.php" style="margin-top: 18px;">
            <?= csrf_input('cancel_bill') ?>
            <?= submission_input('cancel_bill_' . (int) $job['order_id']) ?>
            <input type="hidden" name="order_id" value="<?= (int) $job['order_id'] ?>">
            <?php if ($returnTo !== ''): ?>
                <input type="hidden" name="return_to" value="<?= e($returnTo) ?>">
            <?php endif; ?>
            <div class="field">
                <label for="cancellation_reason"><?= e($reasonFieldLabel) ?></label>
                <textarea id="cancellation_reason" name="cancellation_reason" required></textarea>
            </div>
            <div class="actions">
                <button class="button button-danger" type="submit"><?= e($confirmCancelLabel) ?></button>
                <a class="button button-ghost" href="<?= e($returnTo !== '' ? $returnTo : $defaultReturnPath) ?>"><?= e($keepBillLabel) ?></a>
            </div>
        </form>
    </section>
</div>

<?php render_page_end(); ?>
