<?php
declare(strict_types=1);
require_once __DIR__ . '/../helpers.php';
$userId = as_int(get_query('user_id'));
require_admin($userId);
ensure_void_request_table();
$status = strtolower(get_query('status', 'pending'));
if (!in_array($status, ['pending', 'approved', 'rejected'], true)) {
    $status = 'pending';
}
$conn = db();
$sql = "SELECT vr.id AS request_id, vr.sale_id, s.receipt_no, u.full_name AS requester_name, vr.request_reason, vr.request_status, vr.admin_note, vr.created_at, s.total_amount
        FROM sale_void_requests vr
        INNER JOIN sales s ON s.id = vr.sale_id
        INNER JOIN users u ON u.id = vr.requested_by
        WHERE vr.request_status = ?
        ORDER BY vr.id DESC";
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $status);
$stmt->execute();
$result = $stmt->get_result();
$data = [];
while ($row = $result->fetch_assoc()) {
    $data[] = [
        'request_id' => (int)($row['request_id'] ?? 0),
        'sale_id' => (int)($row['sale_id'] ?? 0),
        'receipt_no' => (string)($row['receipt_no'] ?? ''),
        'requester_name' => (string)($row['requester_name'] ?? ''),
        'request_reason' => (string)($row['request_reason'] ?? ''),
        'request_status' => (string)($row['request_status'] ?? 'pending'),
        'admin_note' => isset($row['admin_note']) ? (string)$row['admin_note'] : null,
        'created_at' => (string)($row['created_at'] ?? ''),
        'total_amount' => (float)($row['total_amount'] ?? 0),
    ];
}
respond(['success' => true, 'data' => $data]);
