<?php

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: subnets.php');
    exit;
}

$id     = (int)($_POST['subnet_id'] ?? 0);
$subnet = Subnet::getById($id);

if (!$subnet) {
    header('Location: subnets.php');
    exit;
}

Subnet::toggle($id);

$newState = $subnet['is_active'] ? 'désactivé' : 'activé';
AuditLog::log('subnet.toggle', 'subnet', $id, $subnet['name'] . ' — ' . $newState);

$sync = SyncService::sync();

$_SESSION['flash'] = [
    'type'    => $sync['success'] ? 'success' : 'warning',
    'message' => "Subnet « {$subnet['name']} » $newState." .
                 ($sync['success'] ? '' : ' Sync : ' . $sync['message']),
];

header('Location: subnets.php');
exit;
