<?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']);

if (!isset($_GET['template'])) {
    foreach (Reservation::getBySubnet($subnet['kea_subnet_id']) as $r) {
        fputcsv($out, [
            $r['mac'],
            $r['ip_address'],
            $r['hostname'],
            $r['description'] ?? '',
        ]);
    }
}

fclose($out);
exit;
