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

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

Auth::requireAuth();

$type = $_GET['type'] ?? '';
$serial = $_GET['serial'] ?? '';
$excludeId = $_GET['exclude_id'] ?? null;

if (!$type || !$serial) {
    echo json_encode(['valid' => false, 'message' => 'Missing required fields']);
    exit;
}

$exists = false;

if ($type === 'weapon') {
    $weaponModel = new WeaponsModel();
    $exists = $weaponModel->checkDuplicateSerial($serial, $excludeId);
} elseif ($type === 'ammunition') {
    // Check ammunition batch number uniqueness if needed
    $exists = Database::fetchOne(
        "SELECT COUNT(*) as count FROM ammunition_inventory WHERE batch_number = ? AND id != ?",
        [$serial, $excludeId ?: 0]
    )['count'] > 0;
}

echo json_encode([
    'valid' => !$exists,
    'exists' => $exists,
    'message' => $exists ? 'Serial number already exists' : 'Serial number is available'
]);