<?php
require_once __DIR__ . '/../config/init.php';

header('Content-Type: application/json');

Auth::requirePermission('returns.view');

$search = $_GET['search'] ?? '';
$status = $_GET['status'] ?? '';

$sql = "SELECT r.*, u.full_name as received_by_name, req.requisition_number
        FROM returns r
        LEFT JOIN users u ON r.received_by = u.id
        LEFT JOIN requisitions req ON r.requisition_id = req.id
        WHERE 1=1";
$params = [];

if ($search) {
    $sql .= " AND (r.return_number LIKE ? OR r.returning_officer_name LIKE ? OR r.returning_unit LIKE ?)";
    $searchTerm = "%$search%";
    $params = array_merge($params, [$searchTerm, $searchTerm, $searchTerm]);
}

if ($status) {
    $sql .= " AND r.status = ?";
    $params[] = $status;
}

$sql .= " ORDER BY r.created_at DESC LIMIT 100";

$returns = Database::fetchAll($sql, $params);

// Get counts for each return
foreach ($returns as &$return) {
    $weapons = Database::fetchOne(
        "SELECT COUNT(*) as count, SUM(arm_total) as total FROM return_weapons WHERE return_id = ?",
        [$return['id']]
    );
    $return['weapons_count'] = $weapons['count'] ?? 0;
    $return['weapons_total'] = $weapons['total'] ?? 0;
    
    $ammo = Database::fetchOne(
        "SELECT COUNT(*) as count, SUM(rounds_returned) as total FROM return_ammunition WHERE return_id = ?",
        [$return['id']]
    );
    $return['ammo_count'] = $ammo['count'] ?? 0;
    $return['ammo_total'] = $ammo['total'] ?? 0;
}

echo json_encode(['success' => true, 'data' => $returns]);