<?php

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

$errors    = [];
$relayMode = Settings::get('relay_mode', '0') === '1';
$data      = [
    'kea_subnet_id' => Subnet::nextAvailableId(), 'name' => '', 'cidr' => '', 'interface' => '',
    'gateway' => '', 'relay_address' => '', 'dns1' => '', 'dns2' => '', 'ntp_servers' => '',
    'range_start' => '', 'range_end' => '', 'has_dynamic_pool' => 0,
    'short_lease_pool_start' => '', 'short_lease_pool_end' => '',
    'notes' => '', 'reserved_ips' => '',
];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $dns1 = trim($_POST['dns1'] ?? '');
    $dns2 = trim($_POST['dns2'] ?? '');
    $data = [
        'kea_subnet_id'   => trim($_POST['kea_subnet_id'] ?? ''),
        'name'            => trim($_POST['name'] ?? ''),
        'cidr'            => trim($_POST['cidr'] ?? ''),
        'interface'       => trim($_POST['interface'] ?? ''),
        'gateway'         => trim($_POST['gateway'] ?? ''),
        'relay_address'   => trim($_POST['relay_address'] ?? ''),
        'dns_servers'     => implode(', ', array_filter([$dns1, $dns2])),
        'dns1'            => $dns1,
        'dns2'            => $dns2,
        'ntp_servers'     => trim($_POST['ntp_servers'] ?? ''),
        'range_start'     => trim($_POST['range_start'] ?? ''),
        'range_end'       => trim($_POST['range_end'] ?? ''),
        'has_dynamic_pool'       => !empty($_POST['has_dynamic_pool']) ? 1 : 0,
        'is_public'              => !empty($_POST['is_public'])        ? 1 : 0,
        'notes'                  => trim($_POST['notes'] ?? ''),
        'reserved_ips'           => trim($_POST['reserved_ips'] ?? ''),
        'short_lease_pool_start' => trim($_POST['short_lease_pool_start'] ?? ''),
        'short_lease_pool_end'   => trim($_POST['short_lease_pool_end']   ?? ''),
    ];

    $errors = Subnet::validate($data);

    if (!$errors) {
        $id   = Subnet::add($data);
        $sync = SyncService::sync();
        AuditLog::log('subnet.add', 'subnet', $id, $data['name'] . ' — ' . $data['cidr']);
        $_SESSION['flash'] = [
            'type'    => $sync['success'] ? 'success' : 'warning',
            'message' => 'Subnet ajouté.' . ($sync['success'] ? '' : ' Sync : ' . $sync['message']),
        ];
        header('Location: subnets.php');
        exit;
    }
}

$page_title = 'Ajouter un subnet';
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="subnets.php" class="text-muted text-decoration-none">
        <i class="bi bi-arrow-left"></i> Subnets
    </a>
</div>

<div class="card">
    <div class="card-header py-3">
        <i class="bi bi-plus-circle me-2"></i>Nouveau subnet
    </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">
            <div class="row g-3 mb-3">
                <div class="col-sm-4">
                    <label class="form-label fw-semibold">ID Kea subnet <span class="text-danger">*</span></label>
                    <input type="number" name="kea_subnet_id" class="form-control"
                           value="<?= h($data['kea_subnet_id']) ?>" min="1" required>
                    <div class="form-text">dhcp4_subnet_id dans Kea</div>
                </div>
                <div class="col-sm-8">
                    <label class="form-label fw-semibold">Nom <span class="text-danger">*</span></label>
                    <input type="text" name="name" class="form-control"
                           value="<?= h($data['name']) ?>"
                           placeholder="LAN principal" required>
                </div>
            </div>

            <div class="row g-3 mb-3">
                <div class="col-sm-6">
                    <label class="form-label fw-semibold">CIDR <span class="text-danger">*</span></label>
                    <input type="text" name="cidr" class="form-control font-monospace"
                           value="<?= h($data['cidr']) ?>"
                           placeholder="192.168.1.0/24" required>
                </div>
                <?php if ($relayMode): ?>
                <div class="col-sm-6">
                    <label class="form-label fw-semibold">
                        Adresse relay (GIADDR) <span class="text-danger">*</span>
                    </label>
                    <input type="text" name="relay_address" class="form-control font-monospace"
                           value="<?= h($data['relay_address']) ?>"
                           placeholder="192.168.10.1">
                    <div class="form-text">IP de l'interface VLAN du switch (GIADDR du paquet relayé — c'est sur cette interface que vous configurez <code>ip helper-address &lt;ip_kea&gt;</code>)</div>
                </div>
                <?php else: ?>
                <div class="col-sm-6">
                    <label class="form-label fw-semibold">Interface</label>
                    <input type="text" name="interface" class="form-control"
                           value="<?= h($data['interface']) ?>"
                           placeholder="igc0.30">
                </div>
                <?php endif; ?>
            </div>

            <div class="row g-3 mb-3">
                <div class="col-sm-6">
                    <label class="form-label fw-semibold">Gateway</label>
                    <input type="text" name="gateway" class="form-control font-monospace"
                           value="<?= h($data['gateway']) ?>"
                           placeholder="192.168.1.1">
                </div>
                <div class="col-sm-6">
                    <label class="form-label fw-semibold">Serveurs DNS</label>
                    <input type="text" name="dns1" class="form-control font-monospace mb-2"
                           value="<?= h($data['dns1']) ?>"
                           placeholder="DNS primaire : 192.168.1.1">
                    <input type="text" name="dns2" class="form-control font-monospace"
                           value="<?= h($data['dns2']) ?>"
                           placeholder="DNS secondaire : 8.8.8.8">
                </div>
            </div>

            <div class="row g-3 mb-3">
                <div class="col-sm-6">
                    <label class="form-label fw-semibold">Serveur NTP</label>
                    <input type="text" name="ntp_servers" class="form-control font-monospace"
                           value="<?= h($data['ntp_servers']) ?>"
                           placeholder="192.168.1.1">
                    <div class="form-text">Option 42 — activable par hôte individuellement</div>
                </div>
            </div>

            <div class="mb-3">
                <div class="form-check">
                    <input type="checkbox" name="has_dynamic_pool" id="has_dynamic_pool"
                           class="form-check-input" value="1"
                           <?= $data['has_dynamic_pool'] ? 'checked' : '' ?>
                           onchange="document.getElementById('pool-range').classList.toggle('d-none', !this.checked)">
                    <label class="form-check-label" for="has_dynamic_pool">
                        Pool DHCP dynamique (en plus des réservations)
                    </label>
                </div>
            </div>

            <div id="pool-range" class="row g-3 mb-3 <?= $data['has_dynamic_pool'] ? '' : 'd-none' ?>">
                <div class="col-sm-6">
                    <label class="form-label fw-semibold">Début du pool</label>
                    <input type="text" name="range_start" class="form-control font-monospace"
                           value="<?= h($data['range_start']) ?>"
                           placeholder="192.168.1.200">
                </div>
                <div class="col-sm-6">
                    <label class="form-label fw-semibold">Fin du pool</label>
                    <input type="text" name="range_end" class="form-control font-monospace"
                           value="<?= h($data['range_end']) ?>"
                           placeholder="192.168.1.250">
                </div>
            </div>

            <div class="row g-2 mb-3">
                <div class="col-12">
                    <label class="form-label fw-semibold">
                        Pool short-lease
                        <small class="text-muted fw-normal">(optionnel — réservé aux hôtes avec lease court 1h)</small>
                    </label>
                </div>
                <div class="col-md-6">
                    <input type="text" name="short_lease_pool_start" class="form-control font-monospace"
                           placeholder="192.168.1.80"
                           value="<?= h($data['short_lease_pool_start'] ?? '') ?>">
                    <div class="form-text">IP de début</div>
                </div>
                <div class="col-md-6">
                    <input type="text" name="short_lease_pool_end" class="form-control font-monospace"
                           placeholder="192.168.1.99"
                           value="<?= h($data['short_lease_pool_end'] ?? '') ?>">
                    <div class="form-text">IP de fin</div>
                </div>
            </div>

            <div class="mb-3">
                <div class="form-check">
                    <input type="checkbox" name="is_public" id="is_public"
                           class="form-check-input" value="1"
                           <?= !empty($data['is_public']) ? 'checked' : '' ?>>
                    <label class="form-check-label" for="is_public">
                        Visible dans le formulaire de demande public
                    </label>
                </div>
                <div class="form-text">Si coché, ce subnet apparaît dans le formulaire accessible sans connexion.</div>
            </div>

            <div class="mb-3">
                <label class="form-label fw-semibold">
                    IP réservées (hors DHCP)
                    <small class="text-muted fw-normal">(optionnel — 1 IP ou plage par ligne, description après #)</small>
                </label>
                <div class="rip-editor" id="rip-editor">
                    <div class="rip-gutter"><div class="rip-gutter-inner" id="rip-gutter"></div></div>
                    <textarea class="rip-ta" name="reserved_ips" id="rip-ta" rows="5" spellcheck="false"
                              placeholder="192.168.1.5 # Imprimante&#10;30-40 # Caméras"><?= h($data['reserved_ips'] ?? '') ?></textarea>
                </div>
                <div class="rip-status" id="rip-status"></div>
                <div class="form-text">Ces IP apparaissent sur le bargraph et bloquent la création d'une réservation dans la plage.</div>
            </div>

            <div class="mb-4">
                <label class="form-label fw-semibold">Notes</label>
                <textarea name="notes" class="form-control" rows="2"><?= h($data['notes']) ?></textarea>
            </div>

            <div class="d-flex gap-2">
                <button type="submit" class="btn btn-primary">
                    <i class="bi bi-check-lg"></i> Enregistrer
                </button>
                <a href="subnets.php" class="btn btn-outline-secondary">Annuler</a>
            </div>
        </form>
    </div>
</div>

</div>
</div>

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

<script src="assets/js/reserved-ips-form.js"></script>
<script>
(function () {
  <?php
    $cidrForm = $data['cidr'] ?? '';
    [$nStr, $bStr] = array_pad(explode('/', $cidrForm ?: '0.0.0.0/32'), 2, '32');
    $bb = (int)$bStr;
    if ($bb < 0 || $bb > 32) { $bb = 32; }
    $mm = $bb >= 32 ? 0xFFFFFFFF : (~((1 << (32 - $bb)) - 1) & 0xFFFFFFFF);
    $netI = (int)sprintf('%u', ip2long($nStr) & $mm);
    $bcI  = $netI + (1 << (32 - $bb)) - 1;
    $sub = [
      'cidr'         => $cidrForm,
      'networkInt'   => $netI,
      'broadcastInt' => $bcI,
      'dynStartInt'  => (!empty($data['has_dynamic_pool']) && !empty($data['range_start'])) ? (int)ipToInt($data['range_start']) : null,
      'dynEndInt'    => (!empty($data['has_dynamic_pool']) && !empty($data['range_end']))   ? (int)ipToInt($data['range_end'])   : null,
      'shortStartInt'=> !empty($data['short_lease_pool_start']) ? (int)ipToInt($data['short_lease_pool_start']) : null,
      'shortEndInt'  => !empty($data['short_lease_pool_end'])   ? (int)ipToInt($data['short_lease_pool_end'])   : null,
    ];
  ?>
  var tip = document.createElement('div'); tip.className = 'rip-tip'; document.body.appendChild(tip);
  ReservedIpsForm.init({
    textarea: document.getElementById('rip-ta'),
    gutter:   document.getElementById('rip-gutter'),
    editor:   document.getElementById('rip-editor'),
    status:   document.getElementById('rip-status'),
    tip:      tip,
    subnet:   <?= json_encode($sub, JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_HEX_AMP) ?>
  });
}());
</script>
