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

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

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

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

if ($search) {
    $weapons = Database::fetchAll(
        "SELECT w.*, wt.type_name 
         FROM weapons_inventory w
         LEFT JOIN weapon_types wt ON w.weapon_type_id = wt.id
         WHERE w.weapon_id LIKE ? 
         OR w.serial_no LIKE ? 
         OR w.make_model LIKE ?
         ORDER BY w.created_at DESC
         LIMIT 50",
        ["%$search%", "%$search%", "%$search%"]
    );
} else {
    $weapons = Database::fetchAll(
        "SELECT w.*, wt.type_name 
         FROM weapons_inventory w
         LEFT JOIN weapon_types wt ON w.weapon_type_id = wt.id
         ORDER BY w.created_at DESC
         LIMIT 50"
    );
}

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