<?php

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

$hostId   = (int)($_GET['id'] ?? 0);
$subnetId = (int)($_GET['subnet_id'] ?? 0);

$reservation = Reservation::getById($hostId);
if (!$reservation) {
    header('Location: dashboard.php');
    exit;
}

$subnet = Subnet::getByKeaSubnetId((int)$reservation['dhcp4_subnet_id']);
if (!$subnet) {
    header('Location: dashboard.php');
    exit;
}
if ($subnetId === 0) {
    $subnetId = $subnet['id'];
}

// Détection d'un lease DHCP actif sur l'IP de la réservation (pour proposer sa libération)
$activeLease = null;
if (!empty($reservation['ip_address'])) {
    $found = LeaseService::findActiveLeases([$reservation['ip_address']]);
    $activeLease = $found[$reservation['ip_address']] ?? null;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['confirm'] ?? '') === '1') {
    $details = sprintf('%s %s (%s) — subnet %s',
        $reservation['mac'], $reservation['ip_address'],
        $reservation['hostname'], $subnet['name']);

    Reservation::delete($hostId);

    $releaseWarning = '';
    if (($_POST['lease_action'] ?? '') === 'release' && !empty($reservation['ip_address'])) {
        $rel = LeaseService::releaseLease($reservation['ip_address']);
        AuditLog::log('lease.release', 'lease', $hostId,
            "IP {$reservation['ip_address']} (MAC {$reservation['mac']}) — depuis reservation_delete");
        if (!$rel['success']) {
            $releaseWarning = ' Lease ' . $reservation['ip_address'] . ' non libéré (' . $rel['message'] . ').';
        }
    }

    $sync = SyncService::sync();
    AuditLog::log('reservation.delete', 'host', $hostId, $details);

    if ($sync['success'] && $releaseWarning === '') {
        $_SESSION['flash'] = ['type' => 'success', 'message' => 'Réservation supprimée et Kea rechargé.'];
    } elseif (!$sync['success']) {
        $_SESSION['flash'] = ['type' => 'warning',
            'message' => 'Réservation supprimée mais le reload Kea a échoué : ' . $sync['message'] . $releaseWarning];
    } else {
        $_SESSION['flash'] = ['type' => 'warning', 'message' => 'Réservation supprimée.' . $releaseWarning];
    }
    header('Location: subnet.php?id=' . $subnetId);
    exit;
}

$page_title = 'Supprimer — ' . h($reservation['hostname']);
require_once APP_ROOT . '/lib/layout_header.php';
?>

<div class="row justify-content-center">
<div class="col-lg-6">

<div class="mb-3">
    <a href="subnet.php?id=<?= $subnetId ?>" class="text-muted text-decoration-none">
        <i class="bi bi-arrow-left"></i> <?= h($subnet['name']) ?>
    </a>
</div>

<div class="card border-danger">
    <div class="card-header bg-danger text-white py-3">
        <i class="bi bi-trash me-2"></i>Confirmer la suppression
    </div>
    <div class="card-body">
        <p>Vous allez supprimer la réservation suivante :</p>
        <table class="table table-sm">
            <tr>
                <th class="text-muted fw-normal" style="width:140px">Hostname</th>
                <td class="fw-semibold"><?= h($reservation['hostname']) ?></td>
            </tr>
            <tr>
                <th class="text-muted fw-normal">Adresse IP</th>
                <td class="font-monospace text-primary"><?= h($reservation['ip_address']) ?></td>
            </tr>
            <tr>
                <th class="text-muted fw-normal">Adresse MAC</th>
                <td class="font-monospace"><?= h($reservation['mac']) ?></td>
            </tr>
            <?php if ($reservation['description']): ?>
            <tr>
                <th class="text-muted fw-normal">Description</th>
                <td><?= h($reservation['description']) ?></td>
            </tr>
            <?php endif; ?>
        </table>

        <div class="alert alert-warning py-2 mt-3">
            <i class="bi bi-exclamation-triangle"></i>
            Cette action est irréversible. La réservation sera supprimée de la base Kea
            et Kea sera rechargé.
        </div>

        <?php if ($activeLease): ?>
        <div class="alert alert-info py-2">
            <i class="bi bi-broadcast me-1"></i>
            Un <strong>lease DHCP actif</strong> existe sur cette IP
            (<code><?= h($reservation['ip_address']) ?></code>, MAC <code><?= h($activeLease['mac']) ?></code><?php if ($activeLease['hostname'] !== ''): ?>, <?= h($activeLease['hostname']) ?><?php endif; ?>).
            Le libérer rend l'adresse immédiatement réutilisable.
        </div>
        <?php endif; ?>

        <form method="post" class="d-flex flex-wrap gap-2 mt-3">
            <input type="hidden" name="confirm" value="1">
            <?php if ($activeLease): ?>
                <button type="submit" name="lease_action" value="ignore" class="btn btn-outline-danger">
                    <i class="bi bi-trash"></i> Supprimer sans libérer
                </button>
                <button type="submit" name="lease_action" value="release" class="btn btn-danger">
                    <i class="bi bi-trash"></i> Supprimer et libérer le lease
                </button>
                <a href="subnet.php?id=<?= $subnetId ?>" class="btn btn-outline-secondary">
                    Annuler
                </a>
            <?php else: ?>
                <button type="submit" class="btn btn-danger">
                    <i class="bi bi-trash"></i> Oui, supprimer
                </button>
                <a href="subnet.php?id=<?= $subnetId ?>" class="btn btn-outline-secondary">
                    Annuler
                </a>
            <?php endif; ?>
        </form>
    </div>
</div>

</div>
</div>

<?php require_once APP_ROOT . '/lib/layout_footer.php'; ?>
