<?php
declare(strict_types=1);

require_once __DIR__ . '/../config/bootstrap.php';

require_login($conn);

ensure_order_branch_column($conn);
ensure_order_return_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);

function bill_receipt_payment_label(array $payment): string
{
    $paymentMethodLabel = quick_service_payment_method_label((string) ($payment['payment_method'] ?? 'cash'));
    $note = trim((string) ($payment['note'] ?? ''));

    if ($note === 'Admin deposit at booking') {
        return localized_text_value('มัดจำ @Admin', 'Deposit @Admin') . ' / ' . $paymentMethodLabel;
    }

    if ($note === 'Branch deposit at booking') {
        return localized_text_value('มัดจำ @Branch', 'Deposit @Branch') . ' / ' . $paymentMethodLabel;
    }

    if ($note === 'Deposit at booking') {
        return localized_text_value('มัดจำ', 'Deposit') . ' / ' . $paymentMethodLabel;
    }

    return $paymentMethodLabel;
}

function bill_receipt_source_label(string $orderSource): string
{
    return $orderSource === 'quick_service'
        ? localized_text_value('ควิกเซอร์วิส', 'Quick Service')
        : localized_text_value('งานจอง', 'Booking');
}

$orderId = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
$returnTo = safe_page_return((string) ($_GET['return_to'] ?? ''), '');
$autoPrint = (int) ($_GET['autoprint'] ?? 0) === 1;

if (!$orderId) {
    redirect_with_flash($returnTo !== '' ? $returnTo : 'dashboard.php', 'error', localized_flash_message('ไม่พบบิล', 'Bill was not found.'));
}

$orderStmt = db_prepare($conn, "
    SELECT
        o.order_id,
        o.bill_number,
        o.customer_id,
        o.car_id,
        o.order_date,
        o.branch_name,
        o.return_at,
        o.status,
        o.payment_status,
        o.order_source,
        o.total_price,
        o.notes,
        c.name AS customer_name,
        c.phone,
        car.plate_number,
        car.province,
        car.brand,
        car.model,
        e.name AS cashier_name
    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
    LEFT JOIN employees e ON e.employee_id = o.employee_id
    WHERE o.order_id = ?
    LIMIT 1
");
$orderStmt->bind_param('i', $orderId);
$orderStmt->execute();
$order = $orderStmt->get_result()->fetch_assoc();
$orderStmt->close();

if (!$order) {
    redirect_with_flash($returnTo !== '' ? $returnTo : 'dashboard.php', 'error', localized_flash_message('ไม่พบบิล', 'Bill was not found.'));
}

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

$orderSource = (string) ($order['order_source'] ?? 'booking');
$canViewBill = can_access($conn, 'bill_management')
    || ($orderSource === 'quick_service' && can_access($conn, 'quick_service'))
    || ($orderSource !== 'quick_service' && can_access($conn, 'queue'));

if (!$canViewBill) {
    redirect_with_flash($returnTo !== '' ? $returnTo : 'dashboard.php', 'error', localized_flash_message('คุณไม่มีสิทธิ์ใช้งานฟังก์ชันนี้', 'You do not have permission to access that function.'));
}

$details = array();
$detailStmt = db_prepare($conn, "
    SELECT service_name_snapshot, price, item_note
    FROM order_details
    WHERE order_id = ?
    ORDER BY detail_id ASC
");
$detailStmt->bind_param('i', $orderId);
$detailStmt->execute();
$detailResult = $detailStmt->get_result();
while ($row = $detailResult->fetch_assoc()) {
    $details[] = $row;
}
$detailStmt->close();

$payments = array();
$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 ASC, payment_id ASC
");
$paymentStmt->bind_param('i', $orderId);
$paymentStmt->execute();
$paymentResult = $paymentStmt->get_result();
while ($row = $paymentResult->fetch_assoc()) {
    $payments[] = $row;
}
$paymentStmt->close();

$paidAmount = 0.0;
$receivedAmount = 0.0;
$changeAmount = 0.0;
foreach ($payments as $payment) {
    $paidAmount += (float) ($payment['amount'] ?? 0);
    $receivedAmount += (float) ($payment['received_amount'] ?? $payment['amount'] ?? 0);
    $changeAmount += (float) ($payment['change_amount'] ?? 0);
}

$totalPrice = (float) ($order['total_price'] ?? 0);
$balanceAmount = max(0.0, $totalPrice - $paidAmount);
$billNumber = trim((string) ($order['bill_number'] ?? ''));
$billLabel = $billNumber !== '' ? $billNumber : '#' . (int) $orderId;
$brandModel = trim((string) (($order['brand'] ?? '') . ' ' . ($order['model'] ?? '')));
$defaultReturnPath = can_access($conn, 'bill_management')
    ? 'bill_management.php'
    : ($orderSource === 'quick_service' ? 'quick_service.php' : 'job_details.php?id=' . $orderId);
$backPath = $returnTo !== '' ? $returnTo : $defaultReturnPath;

$canCancelClosedBill = can_access($conn, 'queue_cancel_closed');
$canCancelOpenBill = can_access($conn, 'queue_cancel_open');
$canCancelWaiting = can_access($conn, 'queue_cancel_waiting');
$isQuickServiceBill = $orderSource === 'quick_service';
$status = (string) ($order['status'] ?? 'waiting');
$paymentStatus = (string) ($order['payment_status'] ?? 'unpaid');
$isWaitingQueueBill = !$isQuickServiceBill && $status === 'waiting';
$isBillClosed = $status === 'done'
    || $paymentStatus === 'paid'
    || ($totalPrice > 0.0 && $balanceAmount <= 0.0);
$canCancelBill = $status !== 'cancelled' && (
    ($isBillClosed && !$isWaitingQueueBill && $canCancelClosedBill)
    || ($isWaitingQueueBill && $canCancelWaiting)
    || (!$isBillClosed && !$isWaitingQueueBill && ($canCancelOpenBill || ($isQuickServiceBill && can_access($conn, 'quick_service'))))
);

$assetPath = dirname(__DIR__) . '/assets';
$cssVersion = is_file($assetPath . '/app.css') ? (string) filemtime($assetPath . '/app.css') : '1';
$pageTitle = localized_text_value('ใบเสร็จบิล', 'Bill Receipt');
$backLabel = localized_text_value('กลับ', 'Back');
$cancelLabel = localized_text_value('ยกเลิกบิล', 'Cancel');
$printReceiptLabel = localized_text_value('พิมพ์ใบเสร็จ', 'Print receipt');
$billNumberLabel = localized_text_value('เลขที่บิล', 'Bill no.');
$sourceLabel = localized_text_value('ที่มา', 'Source');
$dateLabel = localized_text_value('วันที่', 'Date');
$pickupDueLabel = localized_text_value('กำหนดรับรถ', 'Pickup due');
$customerLabel = localized_text_value('ลูกค้า', 'Customer');
$phoneLabel = localized_text_value('เบอร์โทร', 'Phone');
$plateLabel = localized_text_value('ทะเบียน', 'Plate');
$vehicleLabel = localized_text_value('รถ', 'Vehicle');
$statusLabel = localized_text_value('สถานะ', 'Status');
$paymentLabel = localized_text_value('การชำระเงิน', 'Payment');
$cashierLabel = localized_text_value('ผู้รับเงิน', 'Cashier');
$staffLabel = localized_text_value('พนักงาน', 'Staff');
$receivedLabel = localized_text_value('รับมา', 'Received');
$changeLabel = localized_text_value('เงินทอน', 'Change');
$noteLabel = localized_text_value('หมายเหตุ', 'Note');
$billNoteLabel = localized_text_value('หมายเหตุบิล', 'Bill note');
$itemNoteLabel = localized_text_value('หมายเหตุรายการ', 'Item note');
$slipLabel = localized_text_value('สลิป', 'Slip');
$viewSlipLabel = localized_text_value('ดูสลิป', 'View slip');
$totalReceivedLabel = localized_text_value('รับรวม', 'Total received');
$totalChangeLabel = localized_text_value('ทอนรวม', 'Total change');
$paidLabel = localized_text_value('ชำระแล้ว', 'Paid');
$totalLabel = localized_text_value('รวมทั้งสิ้น', 'Total');
$balanceLabel = localized_text_value('คงเหลือ', 'Balance');
$thankYouLabel = localized_text_value('ขอบคุณที่ใช้บริการ', 'Thank you');
?>
<!DOCTYPE html>
<html lang="<?= e(current_language_html_code()) ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= e($pageTitle) ?> | CCW</title>
    <?= render_web_app_meta_tags() . "\n" ?>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Kanit:wght@400;500;600;700&family=Sarabun:wght@300;400;500;600;700&display=swap">
    <link rel="stylesheet" href="../assets/app.css?v=<?= e($cssVersion) ?>">
    <?= render_web_app_bootstrap_script() . "\n" ?>
    <style>
        .receipt-page {
            min-height: 100vh;
            padding: 24px 16px 48px;
            background: #eef3f8;
        }

        .receipt-toolbar {
            display: flex;
            justify-content: center;
            gap: 12px;
            flex-wrap: wrap;
            margin-bottom: 18px;
        }

        .receipt-paper {
            width: min(100%, 340px);
            margin: 0 auto;
            padding: 18px 16px;
            border: 1px dashed #94a7bd;
            border-radius: 14px;
            background: #fff;
            box-shadow: 0 18px 40px rgba(6, 33, 63, 0.08);
            color: #111;
            font-family: "Courier New", monospace;
        }

        .receipt-head,
        .receipt-totals,
        .receipt-footer {
            display: grid;
            gap: 6px;
        }

        .receipt-head {
            text-align: center;
        }

        .receipt-title {
            font-size: 1.15rem;
            font-weight: 700;
        }

        .receipt-line {
            display: flex;
            align-items: flex-start;
            justify-content: space-between;
            gap: 12px;
        }

        .receipt-line strong {
            white-space: nowrap;
        }

        .receipt-line.is-subline {
            padding-left: 14px;
            color: #4f6b8a;
            font-size: 0.9rem;
        }

        .receipt-items {
            display: grid;
            gap: 8px;
            margin: 16px 0;
            padding: 14px 0;
            border-top: 1px dashed #94a7bd;
            border-bottom: 1px dashed #94a7bd;
        }

        .receipt-item {
            display: grid;
            gap: 4px;
        }

        .receipt-footer {
            margin-top: 14px;
            text-align: center;
            font-size: 0.9rem;
        }

        .receipt-screen-link a {
            color: #0b67ff;
            text-decoration: none;
        }

        @media print {
            @page {
                size: 80mm auto;
                margin: 4mm;
            }

            body {
                background: #fff;
            }

            .receipt-toolbar,
            .flash,
            .receipt-screen-link {
                display: none !important;
            }

            .receipt-page {
                padding: 0;
                background: #fff;
            }

            .receipt-paper {
                width: 72mm;
                margin: 0 auto;
                padding: 0;
                border: 0;
                border-radius: 0;
                box-shadow: none;
            }
        }
    </style>
</head>
<body class="receipt-page lang-<?= e(current_language()) ?>">
<div class="receipt-toolbar">
    <a class="button button-secondary" href="<?= e($backPath) ?>"><?= e($backLabel) ?></a>
    <?php if ($canCancelBill): ?>
        <a class="button button-danger" href="cancel_bill.php?id=<?= (int) $orderId ?>&return_to=<?= e(urlencode($backPath)) ?>"><?= e($cancelLabel) ?></a>
    <?php endif; ?>
    <button class="button button-accent" type="button" onclick="window.print()"><?= e($printReceiptLabel) ?></button>
</div>

<article class="receipt-paper">
    <div class="receipt-head">
        <div class="receipt-title">CCW Car Care</div>
        <div><?= e($pageTitle) ?></div>
        <div><?= e((string) ($order['branch_name'] ?? '-')) ?></div>
    </div>

    <div class="receipt-items">
        <div class="receipt-line">
            <span><?= e($billNumberLabel) ?></span>
            <strong><?= e($billLabel) ?></strong>
        </div>
        <div class="receipt-line">
            <span><?= e($sourceLabel) ?></span>
            <strong><?= e(bill_receipt_source_label($orderSource)) ?></strong>
        </div>
        <div class="receipt-line">
            <span><?= e($dateLabel) ?></span>
            <strong><?= e(format_datetime((string) ($order['order_date'] ?? ''))) ?></strong>
        </div>
        <?php if (!empty($order['return_at'])): ?>
            <div class="receipt-line">
                <span><?= e($pickupDueLabel) ?></span>
                <strong><?= e(format_datetime((string) $order['return_at'])) ?></strong>
            </div>
        <?php endif; ?>
        <div class="receipt-line">
            <span><?= e($customerLabel) ?></span>
            <strong><?= e((string) ($order['customer_name'] ?? '-')) ?></strong>
        </div>
        <div class="receipt-line">
            <span><?= e($phoneLabel) ?></span>
            <strong><?= e((string) ($order['phone'] ?? '-')) ?></strong>
        </div>
        <div class="receipt-line">
            <span><?= e($plateLabel) ?></span>
            <strong><?= e((string) ($order['plate_number'] ?? '-')) ?></strong>
        </div>
        <?php if ($brandModel !== ''): ?>
            <div class="receipt-line">
                <span><?= e($vehicleLabel) ?></span>
                <strong><?= e($brandModel) ?></strong>
            </div>
        <?php endif; ?>
        <div class="receipt-line">
            <span><?= e($statusLabel) ?></span>
            <strong><?= e(status_label($status)) ?></strong>
        </div>
        <div class="receipt-line">
            <span><?= e($paymentLabel) ?></span>
            <strong><?= e(payment_status_label($paymentStatus)) ?></strong>
        </div>
        <div class="receipt-line">
            <span><?= e($cashierLabel) ?></span>
            <strong><?= e(trim((string) ($order['cashier_name'] ?? '')) !== '' ? (string) $order['cashier_name'] : $staffLabel) ?></strong>
        </div>
    </div>

    <div class="receipt-items">
        <?php foreach ($details as $detail): ?>
            <div class="receipt-item">
                <div class="receipt-line">
                    <span><?= e((string) ($detail['service_name_snapshot'] ?? '-')) ?></span>
                    <strong><?= format_money($detail['price'] ?? 0) ?></strong>
                </div>
                <?php if (trim((string) ($detail['item_note'] ?? '')) !== ''): ?>
                    <div class="receipt-line is-subline">
                        <span><?= e($itemNoteLabel) ?></span>
                        <strong><?= e(trim((string) $detail['item_note'])) ?></strong>
                    </div>
                <?php endif; ?>
            </div>
        <?php endforeach; ?>
    </div>

    <?php if (!empty($payments)): ?>
        <div class="receipt-totals">
            <?php foreach ($payments as $payment): ?>
                <?php
                $paymentId = (int) ($payment['payment_id'] ?? 0);
                $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'] ?? ''));
                ?>
                <div class="receipt-line">
                    <span><?= e(bill_receipt_payment_label($payment)) ?></span>
                    <strong><?= format_money($payment['amount'] ?? 0) ?></strong>
                </div>
                <?php if ((float) ($payment['received_amount'] ?? 0) > 0): ?>
                    <div class="receipt-line is-subline">
                        <span><?= e($receivedLabel) ?></span>
                        <strong><?= format_money($payment['received_amount'] ?? 0) ?></strong>
                    </div>
                <?php endif; ?>
                <?php if ((float) ($payment['change_amount'] ?? 0) > 0): ?>
                    <div class="receipt-line is-subline">
                        <span><?= e($changeLabel) ?></span>
                        <strong><?= format_money($payment['change_amount'] ?? 0) ?></strong>
                    </div>
                <?php endif; ?>
                <?php if ($paymentNote !== '' && !in_array($paymentNote, array('Admin deposit at booking', 'Branch deposit at booking', 'Deposit at booking'), true)): ?>
                    <div class="receipt-line is-subline">
                        <span><?= e($noteLabel) ?></span>
                        <strong><?= e($paymentNote) ?></strong>
                    </div>
                <?php endif; ?>
                <?php if ($paymentSlipPath !== ''): ?>
                    <div class="receipt-line is-subline receipt-screen-link">
                        <span><?= e($slipLabel) ?></span>
                        <strong><a href="<?= e($paymentSlipPath) ?>" target="_blank" rel="noopener"><?= e($viewSlipLabel) ?></a></strong>
                    </div>
                <?php endif; ?>
            <?php endforeach; ?>
            <div class="receipt-line">
                <span><?= e($totalReceivedLabel) ?></span>
                <strong><?= format_money($receivedAmount) ?></strong>
            </div>
            <?php if ($changeAmount > 0.0): ?>
                <div class="receipt-line">
                    <span><?= e($totalChangeLabel) ?></span>
                    <strong><?= format_money($changeAmount) ?></strong>
                </div>
            <?php endif; ?>
        </div>
    <?php endif; ?>

    <div class="receipt-items">
        <div class="receipt-line">
            <span><?= e($paidLabel) ?></span>
            <strong><?= format_money($paidAmount) ?></strong>
        </div>
        <div class="receipt-line">
            <span><?= e($totalLabel) ?></span>
            <strong><?= format_money($totalPrice) ?></strong>
        </div>
        <?php if ($balanceAmount > 0.0): ?>
            <div class="receipt-line">
                <span><?= e($balanceLabel) ?></span>
                <strong><?= format_money($balanceAmount) ?></strong>
            </div>
        <?php endif; ?>
    </div>

    <?php if (trim((string) ($order['notes'] ?? '')) !== ''): ?>
        <div class="receipt-items">
            <div><?= e($billNoteLabel) ?></div>
            <div><?= nl2br(e((string) $order['notes'])) ?></div>
        </div>
    <?php endif; ?>

    <div class="receipt-footer">
        <div><?= e($thankYouLabel) ?></div>
        <div><?= e($billLabel) ?></div>
    </div>
</article>

<?php if ($autoPrint): ?>
    <script>
        window.addEventListener('load', function () {
            window.print();
        });
    </script>
<?php endif; ?>
</body>
</html>
