<?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::getById($subnetId);
if (!$subnet || $subnet['kea_subnet_id'] !== (int)$reservation['dhcp4_subnet_id']) {
    // Trouver le bon subnet si l'id passé est incorrect
    $subnet = Subnet::getByKeaSubnetId((int)$reservation['dhcp4_subnet_id']);
    if (!$subnet) {
        header('Location: dashboard.php');
        exit;
    }
    $subnetId = $subnet['id'];
}

$errors            = [];
$hasShortLeasePool = !empty($subnet['short_lease_pool_start']);
$data   = [
    'mac'         => $reservation['mac'],
    'ip'          => $reservation['ip_address'],
    'hostname'    => $reservation['hostname'],
    'description' => $reservation['description'] ?? '',
    'gateway'     => $reservation['gateway'] ?? '',
    'no_gateway'  => $reservation['no_gateway'] ?? 0,
    'routes'      => $reservation['routes']  ?? [],
    'ntp_enabled' => $reservation['ntp_enabled'] ?? 0,
    'short_lease' => $reservation['short_lease'] ?? 0,
];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $routesDest = $_POST['routes_dest'] ?? [];
    $routesGw   = $_POST['routes_gw']   ?? [];
    $routes     = [];
    for ($i = 0; $i < max(count($routesDest), count($routesGw)); $i++) {
        $dest = trim($routesDest[$i] ?? '');
        $gw   = trim($routesGw[$i]   ?? '');
        if ($dest !== '' || $gw !== '') {
            $routes[] = ['dest' => $dest, 'gw' => $gw];
        }
    }

    $data = [
        'mac'         => trim($_POST['mac'] ?? ''),
        'ip'          => trim($_POST['ip'] ?? ''),
        'hostname'    => trim($_POST['hostname'] ?? ''),
        'description' => trim($_POST['description'] ?? ''),
        'no_gateway'  => !empty($_POST['no_gateway']) ? 1 : 0,
        'gateway'     => !empty($_POST['no_gateway']) ? '' : trim($_POST['gateway'] ?? ''),
        'routes'      => $routes,
        'ntp_enabled' => !empty($_POST['ntp_enabled']) ? 1 : 0,
        'ntp_value'   => (!empty($_POST['ntp_enabled']) && !empty($subnet['ntp_servers']))
                         ? $subnet['ntp_servers'] : '',
        'short_lease' => !empty($_POST['short_lease']) ? 1 : 0,
    ];

    $errors = Reservation::validate($subnet['kea_subnet_id'], $data, $hostId, $subnet);

    if (!$errors) {
        Reservation::update($hostId, $data);
        $sync = SyncService::sync();
        AuditLog::log(
            'reservation.edit',
            'host',
            $hostId,
            sprintf('%s → %s (%s) sur subnet %s', $data['mac'], $data['ip'], $data['hostname'], $subnet['name'])
        );

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

$page_title = 'Modifier — ' . h($reservation['hostname']);
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">
    <div class="card-header py-3">
        <i class="bi bi-pencil me-2"></i>Modifier la réservation
        <span class="badge bg-secondary ms-2">#<?= $hostId ?></span>
    </div>
    <div class="card-body">
        <?php foreach ($errors as $e): ?>
            <div class="alert alert-danger py-2"><?= h($e) ?></div>
        <?php endforeach; ?>

        <form method="post" autocomplete="off">
            <div class="mb-3">
                <label class="form-label fw-semibold">Adresse MAC <span class="text-danger">*</span></label>
                <input type="text" id="input-mac" name="mac" class="form-control font-monospace"
                       value="<?= h($data['mac']) ?>" required>
                <div id="check-mac" class="form-text mt-1"></div>
            </div>

            <div class="mb-3">
                <label for="input-ip" class="form-label fw-semibold">Adresse IP<?php if (!$hasShortLeasePool): ?> <span class="text-danger">*</span><?php endif; ?></label>
                <div class="input-group">
                    <input type="text" id="input-ip" name="ip" class="form-control font-monospace"
                           value="<?= h($data['ip']) ?>"
                           placeholder="<?= $hasShortLeasePool ? 'Dynamique si vide (pool short-lease)' : '' ?>"
                           <?= (!$hasShortLeasePool || !$data['short_lease']) ? 'required' : '' ?>>
                    <div class="input-group-text">
                        <div class="form-check mb-0">
                            <input type="checkbox" name="short_lease" id="short_lease"
                                   class="form-check-input" value="1"
                                   <?= $data['short_lease'] ? 'checked' : '' ?>>
                            <label class="form-check-label ms-1" for="short_lease">
                                <i class="bi bi-hourglass-split text-warning"></i> Lease court (1h)
                            </label>
                        </div>
                    </div>
                </div>
                <div class="form-text">Subnet : <?= h($subnet['cidr']) ?></div>
                <?php if ($hasShortLeasePool): ?>
                <div class="form-text text-muted" id="short-lease-hint" style="<?= $data['short_lease'] ? '' : 'display:none' ?>">
                    IP optionnelle — le pool <code><?= h($subnet['short_lease_pool_start']) ?> – <?= h($subnet['short_lease_pool_end']) ?></code> sera utilisé.
                </div>
                <?php endif; ?>
                <div id="check-ip" class="form-text mt-1"></div>
            </div>

            <div class="mb-3">
                <label class="form-label fw-semibold">Hostname <span class="text-danger">*</span></label>
                <input type="text" name="hostname" class="form-control"
                       value="<?= h($data['hostname']) ?>" required>
            </div>

            <div class="mb-3">
                <label class="form-label fw-semibold">Description</label>
                <input type="text" name="description" class="form-control"
                       value="<?= h($data['description']) ?>">
            </div>

            <hr class="my-4">
            <h6 class="text-muted mb-3"><i class="bi bi-sliders me-1"></i>Options DHCP spécifiques à cet hôte</h6>

            <div class="mb-3" id="gateway-section">
                <label class="form-label fw-semibold">Gateway spécifique</label>
                <div class="form-text text-muted mb-1">Option 3 — remplace la gateway du subnet pour cet hôte uniquement</div>
                <div class="d-flex flex-wrap gap-2 align-items-center">
                    <input type="text" name="gateway" id="input-gateway" class="form-control font-monospace"
                           style="max-width:200px"
                           value="<?= h($data['gateway']) ?>"
                           placeholder="192.168.1.254"
                           <?= $data['no_gateway'] ? 'disabled' : '' ?>>
                    <div class="form-check mb-0">
                        <input type="checkbox" name="no_gateway" id="no_gateway"
                               class="form-check-input" value="1"
                               <?= $data['no_gateway'] ? 'checked' : '' ?>>
                        <label class="form-check-label text-danger" for="no_gateway">
                            <i class="bi bi-slash-circle me-1"></i>Ne pas envoyer de gateway
                        </label>
                    </div>
                </div>
                <div id="no-gateway-info" class="form-text text-danger mt-1 <?= $data['no_gateway'] ? '' : 'd-none' ?>">
                    <i class="bi bi-info-circle"></i> La gateway du subnet ne sera <strong>pas transmise</strong> à cet hôte (option 3 supprimée).
                </div>
            </div>

            <div class="mb-4">
                <label class="form-label fw-semibold">Routes statiques</label>
                <div class="form-text text-muted mb-2">Option 121 — routes envoyées uniquement à cet hôte (ex : 10.0.0.0/8 via 192.168.1.254)</div>
                <div id="routes-container"></div>
                <button type="button" class="btn btn-sm btn-outline-secondary mt-1" id="add-route">
                    <i class="bi bi-plus-lg"></i> Ajouter une route
                </button>
                <div id="route-default-warning" class="alert alert-warning py-2 px-3 mt-2 mb-0 d-none">
                    <i class="bi bi-exclamation-triangle-fill me-1"></i>
                    <strong>RFC 3442</strong> — Quand des routes statiques sont présentes, le client ignore la gateway du subnet.
                    <span id="route-default-missing">
                        La route par défaut n'est pas définie.
                        <button type="button" id="add-default-route" class="btn btn-sm btn-warning ms-2">
                            <i class="bi bi-plus-lg"></i> Ajouter 0.0.0.0/0 → <?= h($subnet['gateway'] ?: '…') ?>
                        </button>
                    </span>
                    <span id="route-default-present" class="d-none">
                        <i class="bi bi-check-circle-fill text-success ms-1"></i> Route par défaut présente.
                    </span>
                </div>
            </div>

            <?php if (!empty($subnet['ntp_servers'])): ?>
            <div class="mb-4">
                <div class="form-check">
                    <input type="checkbox" name="ntp_enabled" id="ntp_enabled"
                           class="form-check-input" value="1"
                           <?= $data['ntp_enabled'] ? 'checked' : '' ?>>
                    <label class="form-check-label" for="ntp_enabled">
                        <i class="bi bi-clock me-1 text-info"></i>
                        Activer NTP pour cet hôte (option 42)
                    </label>
                </div>
                <div class="form-text text-muted">Serveur NTP du subnet : <code><?= h($subnet['ntp_servers']) ?></code></div>
            </div>
            <?php endif; ?>

            <div class="d-flex gap-2">
                <button type="submit" class="btn btn-primary">
                    <i class="bi bi-check-lg"></i> Enregistrer les modifications
                </button>
                <a href="subnet.php?id=<?= $subnetId ?>" class="btn btn-outline-secondary">
                    Annuler
                </a>
                <a href="reservation_delete.php?id=<?= $hostId ?>&subnet_id=<?= $subnetId ?>"
                   class="btn btn-outline-danger ms-auto">
                    <i class="bi bi-trash"></i> Supprimer
                </a>
            </div>
        </form>
    </div>
</div>

</div>
</div>

<?php require_once APP_ROOT . '/lib/layout_footer.php'; ?>
<script>
(function () {
    var SUBNET_ID      = <?= (int)$subnetId ?>;
    var EXCLUDE_ID     = <?= (int)$hostId ?>;
    var SUBNET_GW      = <?= json_encode($subnet['gateway'] ?? '') ?>;
    var INITIAL_ROUTES = <?= json_encode($data['routes']) ?>;

    // ── Vérification doublons MAC / IP ────────────────────────────────────────
    function checkDup(inputId, feedbackId, type) {
        var el = document.getElementById(inputId);
        var fb = document.getElementById(feedbackId);
        el.addEventListener('blur', function () {
            var val = this.value.trim();
            fb.textContent = '';
            el.classList.remove('is-valid', 'is-invalid');
            if (!val) return;
            var url = 'api_check_duplicate.php?type=' + type
                + '&value=' + encodeURIComponent(val)
                + '&subnet_id=' + SUBNET_ID
                + '&exclude_host_id=' + EXCLUDE_ID;
            fetch(url)
                .then(function (r) { return r.json(); })
                .then(function (d) {
                    if (d.duplicate) {
                        el.classList.add('is-invalid');
                        fb.className = 'form-text text-danger mt-1';
                        fb.innerHTML = '<i class="bi bi-x-circle-fill"></i> ' + d.message;
                    } else if (!d.invalid) {
                        el.classList.add('is-valid');
                        fb.className = 'form-text text-success mt-1';
                        fb.innerHTML = '<i class="bi bi-check-circle-fill"></i> Disponible';
                    }
                })
                .catch(function () {});
        });
    }

    checkDup('input-mac', 'check-mac', 'mac');
    checkDup('input-ip',  'check-ip',  'ip');

    // ── Routes statiques ──────────────────────────────────────────────────────
    var container      = document.getElementById('routes-container');
    var warning        = document.getElementById('route-default-warning');
    var wMissing       = document.getElementById('route-default-missing');
    var wPresent       = document.getElementById('route-default-present');
    var gatewaySection = document.getElementById('gateway-section');

    function escHtml(s) {
        return String(s)
            .replace(/&/g, '&amp;').replace(/</g, '&lt;')
            .replace(/>/g, '&gt;').replace(/"/g, '&quot;');
    }

    function hasDefaultRoute() {
        var inputs = container.querySelectorAll('input[name="routes_dest[]"]');
        for (var i = 0; i < inputs.length; i++) {
            if (inputs[i].value.trim() === '0.0.0.0/0') return true;
        }
        return false;
    }

    // ── No-gateway checkbox ───────────────────────────────────────────────────
    var noGatewayChk  = document.getElementById('no_gateway');
    var noGatewayInfo = document.getElementById('no-gateway-info');
    var inputGateway  = document.getElementById('input-gateway');

    function updateNoGateway() {
        var checked = noGatewayChk.checked;
        inputGateway.disabled = checked;
        if (checked) {
            inputGateway.value = '';
            noGatewayInfo.classList.remove('d-none');
        } else {
            noGatewayInfo.classList.add('d-none');
        }
    }
    noGatewayChk.addEventListener('change', updateNoGateway);

    function updateRouteWarning() {
        var rows = container.querySelectorAll('.route-row');
        var hasRoutes = rows.length > 0;
        // Masquer toute la section gateway (spécifique + no_gateway) si des routes sont présentes
        gatewaySection.classList.toggle('d-none', hasRoutes);
        if (hasRoutes) {
            inputGateway.value = '';
            noGatewayChk.checked = false;
            noGatewayInfo.classList.add('d-none');
            inputGateway.disabled = false;
        }
        if (!hasRoutes) {
            warning.classList.add('d-none');
            return;
        }
        warning.classList.remove('d-none');
        if (hasDefaultRoute()) {
            wMissing.classList.add('d-none');
            wPresent.classList.remove('d-none');
        } else {
            wMissing.classList.remove('d-none');
            wPresent.classList.add('d-none');
        }
    }

    function addRoute(dest, gw) {
        var row = document.createElement('div');
        row.className = 'd-flex gap-2 mb-2 align-items-center route-row';
        row.innerHTML =
            '<input type="text" name="routes_dest[]" value="' + escHtml(dest || '') + '" '
            + 'placeholder="10.0.0.0/8" class="form-control font-monospace" style="max-width:185px">'
            + '<span class="text-muted px-1">→</span>'
            + '<input type="text" name="routes_gw[]" value="' + escHtml(gw || '') + '" '
            + 'placeholder="192.168.1.254" class="form-control font-monospace" style="max-width:175px">'
            + '<button type="button" class="btn btn-sm btn-outline-danger remove-route" title="Supprimer">'
            + '<i class="bi bi-x-lg"></i></button>';
        container.appendChild(row);
        row.querySelector('.remove-route').addEventListener('click', function () {
            row.remove();
            updateRouteWarning();
        });
        row.querySelector('input[name="routes_dest[]"]').addEventListener('input', updateRouteWarning);
        updateRouteWarning();
    }

    INITIAL_ROUTES.forEach(function (r) { addRoute(r.dest, r.gw); });

    document.getElementById('add-route').addEventListener('click', function () {
        addRoute('', '');
    });

    document.getElementById('add-default-route').addEventListener('click', function () {
        addRoute('0.0.0.0/0', SUBNET_GW);
    });

    // ── Short-lease pool : rend l'IP optionnelle ──────────────────────────────
    <?php if ($hasShortLeasePool): ?>
    var shortLeaseChk  = document.getElementById('short_lease');
    var ipField        = document.getElementById('input-ip');
    var shortLeaseHint = document.getElementById('short-lease-hint');

    function updateIpRequired() {
        if (shortLeaseChk.checked) {
            ipField.required = false;
            ipField.placeholder = 'Dynamique si vide (pool short-lease)';
            if (shortLeaseHint) shortLeaseHint.style.display = '';
        } else {
            ipField.required = true;
            ipField.placeholder = '';
            if (shortLeaseHint) shortLeaseHint.style.display = 'none';
        }
    }
    shortLeaseChk.addEventListener('change', updateIpRequired);
    updateIpRequired();
    <?php endif; ?>
}());
</script>
