<?php

require_once __DIR__ . '/../lib/init.php';
Auth::requireLogin();

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

$slug     = preg_replace('/[^a-z0-9]+/', '-', strtolower($subnet['name']));
$filename = 'reservations-' . $slug . '.csv';

header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Cache-Control: no-cache, no-store');

$out = fopen('php://output', 'w');
// BOM UTF-8 pour compatibilité Excel
fwrite($out, "\xEF\xBB\xBF");
fputcsv($out, ['mac', 'ip', 'hostname', 'description', 'group', 'gateway', 'routes', 'short_lease', 'no_gateway'], ',', '"', '');

if (!isset($_GET['template'])) {
    foreach (Reservation::getBySubnet($subnet['kea_subnet_id']) as $r) {
        $full    = Reservation::getById((int)$r['host_id']);
        $gateway = $full['gateway'] ?? '';
        $routes  = '';
        if (!empty($full['routes'])) {
            $parts = [];
            foreach ($full['routes'] as $route) {
                $parts[] = $route['dest'] . '-' . $route['gw'];
            }
            $routes = implode('|', $parts);
        }
        // ipv4_address = 0 → IP dynamique (pool short-lease), exporter vide
        $ipStr = ($r['ip_address'] !== '' && $r['ip_address'] !== '0.0.0.0') ? $r['ip_address'] : '';
        fputcsv($out, [
            $r['mac'],
            $ipStr,
            $r['hostname'],
            $r['description'] ?? '',
            $r['group_name'] ?? '',
            $gateway,
            $routes,
            $r['short_lease'] ? '1' : '0',
            !empty($full['no_gateway']) ? '1' : '0',
        ], ',', '"', '');
    }
}

fclose($out);
exit;
