<?php

require_once __DIR__ . '/../lib/init.php';
Auth::requireLogin();
Auth::requireRole('admin', 'tech');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: leases.php');
    exit;
}

$ip  = trim($_POST['ip']  ?? '');
$mac = trim($_POST['mac'] ?? '');

if ($ip === '' || !filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
    $_SESSION['flash'] = ['type' => 'danger', 'message' => 'Adresse IP invalide.'];
    header('Location: leases.php');
    exit;
}

$res = LeaseService::releaseLease($ip);

if ($res['success']) {
    $msg = $res['existed']
        ? "Lease $ip libéré."
        : "Lease $ip déjà expiré (rien à libérer).";
    $_SESSION['flash'] = ['type' => 'success', 'message' => $msg];
    AuditLog::log('lease.release', 'lease', null,
        "IP $ip" . ($mac !== '' ? " (MAC $mac)" : '') . ' — depuis leases.php');
} else {
    $_SESSION['flash'] = ['type' => 'danger', 'message' => 'Lease non libéré : ' . $res['message']];
}

header('Location: leases.php');
exit;
