<?php
declare(strict_types=1);
require_once __DIR__ . '/../helpers.php';
$userId = as_int(get_query('user_id'));
require_user($userId);
$saleId = as_int(get_query('sale_id'));
if ($saleId <= 0) {
    respond(['success' => false, 'message' => 'Sale ID is required.'], 400);
}
$conn = db();
$statusSelect = sales_status_select_sql('sales') . ' AS sale_status';
$notesSelect = table_has_column('sales', 'notes') ? ', notes' : '';
$statusReasonSelect = table_has_column('sales', 'status_reason') ? ', status_reason' : '';
$sql = "SELECT id AS sale_id, receipt_no, total_amount, payment_amount, change_amount, sale_datetime, cashier_name, {$statusSelect}{$statusReasonSelect}{$notesSelect} FROM sales WHERE id = ? LIMIT 1";
$stmt = $conn->prepare($sql);
if (!$stmt) {
    respond(['success' => false, 'message' => 'Unable to load receipt.'], 500);
}
$stmt->bind_param('i', $saleId);
$stmt->execute();
$sale = $stmt->get_result()->fetch_assoc();
if (!$sale) {
    respond(['success' => false, 'message' => 'Receipt not found.'], 404);
}
$itemStmt = $conn->prepare('SELECT item_id, sku, item_name AS name, price, quantity, line_total FROM sale_items WHERE sale_id = ? ORDER BY id ASC');
$itemStmt->bind_param('i', $saleId);
$itemStmt->execute();
$itemResult = $itemStmt->get_result();
$items = [];
while ($row = $itemResult->fetch_assoc()) {
    $items[] = [
        'item_id' => isset($row['item_id']) ? (int)$row['item_id'] : null,
        'sku' => isset($row['sku']) ? (string)$row['sku'] : null,
        'name' => (string)($row['name'] ?? ''),
        'price' => (float)($row['price'] ?? 0),
        'quantity' => (int)($row['quantity'] ?? 0),
        'line_total' => (float)($row['line_total'] ?? 0),
    ];
}
respond(['success' => true, 'data' => [
    'sale_id' => (int)($sale['sale_id'] ?? 0),
    'receipt_no' => (string)($sale['receipt_no'] ?? ''),
    'total_amount' => (float)($sale['total_amount'] ?? 0),
    'payment_amount' => (float)($sale['payment_amount'] ?? 0),
    'change_amount' => (float)($sale['change_amount'] ?? 0),
    'sale_datetime' => (string)($sale['sale_datetime'] ?? ''),
    'cashier_name' => (string)($sale['cashier_name'] ?? ''),
    ...sale_status_payload_from_row($sale),
    'items' => $items,
]]);
