<?php

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

$id     = (int)($_GET['id'] ?? 0);
$subnet = Subnet::getById($id);
if (!$subnet) {
    header('Location: subnets.php');
    exit;
}

$reservationCount = (int)$subnet['reservation_count'];

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['confirm'] ?? '') === '1') {
    $deleteReservations = !empty($_POST['delete_reservations']);
    $deleted = 0;

    if ($reservationCount > 0 && $deleteReservations) {
        $deleted = Reservation::deleteBySubnet((int)$subnet['kea_subnet_id']);
    } elseif ($reservationCount > 0 && !$deleteReservations) {
        // Sécurité : si des réservations existent et l'option n'est pas cochée, bloquer
        $_SESSION['flash'] = [
            'type'    => 'danger',
            'message' => 'Suppression annulée : le subnet contient encore ' . $reservationCount . ' réservation(s).',
        ];
        header('Location: subnets.php');
        exit;
    }

    Subnet::delete($id);
    $sync = SyncService::sync();
    $detail = $subnet['name'] . ' — ' . $subnet['cidr'];
    if ($deleted) $detail .= " ($deleted réservation(s) supprimée(s))";
    AuditLog::log('subnet.delete', 'subnet', $id, $detail);
    $_SESSION['flash'] = [
        'type'    => $sync['success'] ? 'success' : 'warning',
        'message' => 'Subnet supprimé.' . ($deleted ? " $deleted réservation(s) supprimée(s)." : '') . ($sync['success'] ? '' : ' Sync : ' . $sync['message']),
    ];
    header('Location: subnets.php');
    exit;
}

$page_title = 'Supprimer — ' . h($subnet['name']);
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="subnets.php" class="text-muted text-decoration-none">
        <i class="bi bi-arrow-left"></i> Subnets
    </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>Supprimer le subnet
    </div>
    <div class="card-body">
        <p>Vous allez supprimer le subnet :</p>
        <table class="table table-sm">
            <tr><th class="text-muted fw-normal" style="width:140px">Nom</th>
                <td class="fw-semibold"><?= h($subnet['name']) ?></td></tr>
            <tr><th class="text-muted fw-normal">CIDR</th>
                <td><code><?= h($subnet['cidr']) ?></code></td></tr>
            <tr><th class="text-muted fw-normal">ID Kea</th>
                <td><?= $subnet['kea_subnet_id'] ?></td></tr>
            <tr><th class="text-muted fw-normal">Réservations</th>
                <td>
                    <?php if ($reservationCount > 0): ?>
                        <span class="badge bg-warning text-dark"><?= $reservationCount ?></span>
                    <?php else: ?>
                        <span class="text-muted">0</span>
                    <?php endif; ?>
                </td></tr>
        </table>

        <?php if ($reservationCount > 0): ?>
        <div class="alert alert-warning py-2 mt-2">
            <i class="bi bi-exclamation-triangle me-1"></i>
            Ce subnet contient <strong><?= $reservationCount ?> réservation(s)</strong>.
            Cochez l'option ci-dessous pour les supprimer, sinon la suppression sera bloquée.
        </div>
        <?php else: ?>
        <div class="alert alert-warning py-2 mt-2">
            <i class="bi bi-exclamation-triangle"></i>
            Seules les métadonnées applicatives seront supprimées.
            Les entrées Kea ne sont pas affectées.
        </div>
        <?php endif; ?>

        <form method="post" class="mt-3">
            <input type="hidden" name="confirm" value="1">

            <?php if ($reservationCount > 0): ?>
            <div class="form-check mb-3">
                <input type="checkbox" name="delete_reservations" id="delete_reservations"
                       class="form-check-input" value="1" required>
                <label class="form-check-label text-danger fw-semibold" for="delete_reservations">
                    Supprimer aussi les <?= $reservationCount ?> réservation(s) du subnet
                </label>
            </div>
            <?php endif; ?>

            <div class="d-flex gap-2">
                <button type="submit" class="btn btn-danger">
                    <i class="bi bi-trash"></i> Oui, supprimer
                </button>
                <a href="subnets.php" class="btn btn-outline-secondary">Annuler</a>
                <?php if ($reservationCount > 0): ?>
                <a href="subnet.php?id=<?= $id ?>" class="btn btn-outline-secondary ms-auto">
                    Voir les réservations
                </a>
                <?php endif; ?>
            </div>
        </form>
    </div>
</div>

</div>
</div>

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