<?php

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

// ── Entrée : subnet + liste de host_ids (POST depuis la barre de sélection) ──────
$subnetId = (int)($_POST['subnet_id'] ?? 0);
$subnet   = Subnet::getById($subnetId);
if (!$subnet) {
    header('Location: subnets.php');
    exit;
}

// Parse et valide les host_ids : uniquement des réservations RÉELLES de CE subnet.
$rawIds = array_filter(array_map('intval', explode(',', (string)($_POST['host_ids'] ?? ''))));
$reservations = [];
foreach (array_unique($rawIds) as $hid) {
    if ($hid <= 0) continue;
    $r = Reservation::getById($hid);
    if ($r && (int)$r['dhcp4_subnet_id'] === (int)$subnet['kea_subnet_id']) {
        $reservations[] = $r;
    }
}

if (!$reservations) {
    $_SESSION['flash'] = ['type' => 'warning', 'message' => 'Aucune réservation valide à supprimer.'];
    header('Location: subnet.php?id=' . $subnetId);
    exit;
}

// Détection des leases DHCP actifs sur les IP concernées (pour proposer leur libération).
$ips = [];
foreach ($reservations as $r) {
    if (!empty($r['ip_address'])) { $ips[] = $r['ip_address']; }
}
$activeLeases = $ips ? LeaseService::findActiveLeases($ips) : [];

// ── Exécution (2e POST, confirmé) ───────────────────────────────────────────────
if (($_POST['confirm'] ?? '') === '1') {
    $leaseAction   = $_POST['lease_action'] ?? '';
    $deleted       = 0;
    $releaseWarning = '';

    foreach ($reservations as $r) {
        Reservation::delete((int)$r['host_id']);
        $deleted++;

        if ($leaseAction === 'release' && !empty($r['ip_address']) && isset($activeLeases[$r['ip_address']])) {
            $rel = LeaseService::releaseLease($r['ip_address']);
            AuditLog::log('lease.release', 'lease', (int)$r['host_id'],
                "IP {$r['ip_address']} (MAC {$r['mac']}) — depuis reservation_mass_delete");
            if (!$rel['success']) {
                $releaseWarning = ' Certains leases n\'ont pas pu être libérés.';
            }
        }
    }

    $sync = SyncService::sync();
    AuditLog::log('reservation.mass_delete', 'subnet', $subnetId,
        "$deleted réservation(s) supprimée(s) sur subnet {$subnet['name']}"
        . ($leaseAction === 'release' ? ' (+ libération des leases actifs)' : ''));

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

// ── Page de confirmation (1er POST) ─────────────────────────────────────────────
$hostIdsCsv = implode(',', array_map(function ($r) { return (int)$r['host_id']; }, $reservations));
$page_title = 'Supprimer ' . count($reservations) . ' réservation(s)';
require_once APP_ROOT . '/lib/layout_header.php';
?>

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

<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 de <?= count($reservations) ?> réservation(s)
    </div>
    <div class="card-body">
        <p>Vous allez supprimer les réservations suivantes :</p>
        <div class="table-responsive" style="max-height:340px;overflow-y:auto">
            <table class="table table-sm">
                <thead class="table-light">
                    <tr><th>Hostname</th><th>IP</th><th>MAC</th><th></th></tr>
                </thead>
                <tbody>
                    <?php foreach ($reservations as $r): ?>
                    <tr>
                        <td><?= h($r['hostname']) ?></td>
                        <td class="font-monospace text-primary"><?= h($r['ip_address']) ?></td>
                        <td class="font-monospace small"><?= h($r['mac']) ?></td>
                        <td>
                            <?php if (!empty($r['ip_address']) && isset($activeLeases[$r['ip_address']])): ?>
                                <span class="badge bg-warning text-dark" title="Un lease DHCP est actif sur cette IP">
                                    <i class="bi bi-broadcast"></i> lease actif
                                </span>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

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

        <?php if ($activeLeases): ?>
        <div class="alert alert-info py-2">
            <i class="bi bi-broadcast me-1"></i>
            <strong><?= count($activeLeases) ?> lease(s) DHCP actif(s)</strong> sur les IP sélectionnées.
            Les libérer rend ces adresses immédiatement réutilisables.
        </div>
        <?php endif; ?>

        <form method="post" class="d-flex flex-wrap gap-2 mt-3">
            <input type="hidden" name="subnet_id" value="<?= $subnetId ?>">
            <input type="hidden" name="host_ids" value="<?= h($hostIdsCsv) ?>">
            <input type="hidden" name="confirm" value="1">
            <?php if ($activeLeases): ?>
                <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 les leases
                </button>
            <?php else: ?>
                <button type="submit" class="btn btn-danger">
                    <i class="bi bi-trash"></i> Oui, supprimer
                </button>
            <?php endif; ?>
            <a href="subnet.php?id=<?= $subnetId ?>" class="btn btn-outline-secondary">
                Annuler
            </a>
        </form>
    </div>
</div>

</div>
</div>

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