<?php
declare(strict_types=1);
require_once __DIR__ . '/../helpers.php';
$userId = as_int(get_query('user_id'));
require_user($userId);
$receiptNo = get_query('receipt_no');
$saleDate = get_query('sale_date');
if ($receiptNo === '' && $saleDate === '') {
    respond(['success' => false, 'message' => 'Receipt number or sale date is required.'], 400);
}
if ($saleDate !== '' && !valid_date($saleDate)) {
    respond(['success' => false, 'message' => 'Invalid sale date format. Use YYYY-MM-DD.'], 400);
}
$conn = db();
ensure_void_request_table();
$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}, EXISTS(SELECT 1 FROM sale_void_requests vr WHERE vr.sale_id = sales.id AND vr.request_status = 'pending') AS pending_void_request FROM sales WHERE 1=1";
$params = [];
$types = '';
if ($receiptNo !== '') {
    $sql .= " AND receipt_no LIKE ?";
    $params[] = '%' . $receiptNo . '%';
    $types .= 's';
}
if ($saleDate !== '') {
    $sql .= " AND DATE(sale_datetime) = ?";
    $params[] = $saleDate;
    $types .= 's';
}
$sql .= " ORDER BY sale_datetime DESC LIMIT 100";
$stmt = $conn->prepare($sql);
if (!$stmt) {
    respond(['success' => false, 'message' => 'Unable to search receipts.'], 500);
}
if ($types !== '') {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$result = $stmt->get_result();
$data = [];
while ($row = $result->fetch_assoc()) {
    $data[] = [
        'sale_id' => (int)($row['sale_id'] ?? 0),
        'receipt_no' => (string)($row['receipt_no'] ?? ''),
        'total_amount' => (float)($row['total_amount'] ?? 0),
        'payment_amount' => (float)($row['payment_amount'] ?? 0),
        'change_amount' => (float)($row['change_amount'] ?? 0),
        'sale_datetime' => (string)($row['sale_datetime'] ?? ''),
        'cashier_name' => (string)($row['cashier_name'] ?? ''),
        'pending_void_request' => ((int)($row['pending_void_request'] ?? 0)) === 1,
        ...sale_status_payload_from_row($row),
    ];
}
respond(['success' => true, 'data' => $data]);
