<?php

require_once __DIR__ . '/../lib/init.php';
Auth::requireLogin();

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

$type      = $_GET['type']            ?? '';
$value     = trim($_GET['value']      ?? '');
$subnetId  = (int)($_GET['subnet_id'] ?? 0);
$excludeId = (int)($_GET['exclude_host_id'] ?? 0) ?: null;

if (!in_array($type, ['mac', 'ip'], true) || !$subnetId) {
    echo json_encode(['duplicate' => false]);
    exit;
}
// IP vide = allocation dynamique (short-lease sans IP fixe) — pas de doublon possible
if ($type === 'ip' && $value === '') {
    echo json_encode(['duplicate' => false]);
    exit;
}
if ($value === '') {
    echo json_encode(['duplicate' => false]);
    exit;
}

$subnet = Subnet::getById($subnetId);
if (!$subnet) {
    echo json_encode(['duplicate' => false]);
    exit;
}

$keaSubnetId = (int)$subnet['kea_subnet_id'];
$db          = Database::get();

if ($type === 'mac') {
    if (!isValidMac($value)) {
        echo json_encode(['duplicate' => false, 'invalid' => true]);
        exit;
    }
    $binary = macToBinary($value);
    $sql    = 'SELECT host_id FROM hosts WHERE dhcp4_subnet_id = ? AND dhcp_identifier = ?'
            . ' AND dhcp_identifier_type = ' . Reservation::HW_ADDR_TYPE
            . ($excludeId ? ' AND host_id <> ' . $excludeId : '');
    $stmt = $db->prepare($sql);
    $stmt->execute([$keaSubnetId, $binary]);
    $found = $stmt->fetch();
    echo json_encode([
        'duplicate' => (bool)$found,
        'message'   => $found ? 'Ce MAC est déjà réservé sur ce subnet.' : '',
    ]);
} else {
    if (!isValidIp($value)) {
        echo json_encode(['duplicate' => false, 'invalid' => true]);
        exit;
    }
    $ipInt = ipToInt($value);

    // Vérification pool dynamique
    if ($subnet['has_dynamic_pool'] && $subnet['range_start'] && $subnet['range_end']) {
        $startInt = ipToInt($subnet['range_start']);
        $endInt   = ipToInt($subnet['range_end']);
        if ($ipInt >= $startInt && $ipInt <= $endInt) {
            echo json_encode([
                'duplicate' => true,
                'message'   => 'IP dans le pool dynamique (' . $subnet['range_start'] . ' – ' . $subnet['range_end'] . ').',
            ]);
            exit;
        }
    }

    $sql  = 'SELECT host_id FROM hosts WHERE dhcp4_subnet_id = ? AND ipv4_address = ?'
          . ($excludeId ? ' AND host_id <> ' . $excludeId : '');
    $stmt = $db->prepare($sql);
    $stmt->execute([$keaSubnetId, $ipInt]);
    $found = $stmt->fetch();
    echo json_encode([
        'duplicate' => (bool)$found,
        'message'   => $found ? 'Cette IP est déjà réservée sur ce subnet.' : '',
    ]);
}
