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

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

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

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

if ($search) {
    $ammunition = Database::fetchAll(
        "SELECT a.*, at.ammo_type, ac.calibre
         FROM ammunition_inventory a
         LEFT JOIN ammunition_types at ON a.ammo_type_id = at.id
         LEFT JOIN ammunition_calibres ac ON a.calibre_id = ac.id
         WHERE a.ammo_id LIKE ? 
         OR a.batch_number LIKE ?
         OR at.ammo_type LIKE ?
         OR ac.calibre LIKE ?
         ORDER BY a.created_at DESC
         LIMIT 50",
        ["%$search%", "%$search%", "%$search%", "%$search%"]
    );
} else {
    $ammunition = Database::fetchAll(
        "SELECT a.*, at.ammo_type, ac.calibre
         FROM ammunition_inventory a
         LEFT JOIN ammunition_types at ON a.ammo_type_id = at.id
         LEFT JOIN ammunition_calibres ac ON a.calibre_id = ac.id
         ORDER BY a.created_at DESC
         LIMIT 50"
    );
}

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