<?php
require_once __DIR__ . '/helpers.php';

/**
 * Construit l'objet passé à SubnetBargraph.init (bornes entières, pools, reservedIps,
 * total, addUrl). Extrait de subnet.php pour réemploi (subnet_copy, subnet_import mono).
 *
 * @param array $subnet ligne app_subnets (id, cidr, has_dynamic_pool, range_start/end,
 *                       short_lease_pool_start/end, reserved_ips)
 */
function buildBargraphSubnet(array $subnet): array {
    [$netStr, $bitsStr] = array_pad(explode('/', $subnet['cidr']), 2, '32');
    $bits        = (int)$bitsStr;
    $maskLong    = $bits >= 32 ? 0xFFFFFFFF : (~((1 << (32 - $bits)) - 1) & 0xFFFFFFFF);
    $networkInt  = (int)sprintf('%u', ip2long($netStr) & $maskLong);
    $hostCount   = 1 << (32 - $bits);
    $broadcast   = $networkInt + $hostCount - 1;
    $firstUsable = $bits >= 31 ? $networkInt : $networkInt + 1;
    $lastUsable  = $bits >= 31 ? $broadcast : $broadcast - 1;
    return [
        'cidr'          => $subnet['cidr'],
        'networkInt'    => $networkInt,
        'broadcastInt'  => $broadcast,
        'firstUsable'   => $firstUsable,
        'lastUsable'    => $lastUsable,
        'total'         => $lastUsable - $firstUsable + 1,
        'dynStartInt'   => ($subnet['has_dynamic_pool'] && $subnet['range_start']) ? (int)ipToInt($subnet['range_start']) : null,
        'dynEndInt'     => ($subnet['has_dynamic_pool'] && $subnet['range_end'])   ? (int)ipToInt($subnet['range_end'])   : null,
        'shortStartInt' => !empty($subnet['short_lease_pool_start']) ? (int)ipToInt($subnet['short_lease_pool_start']) : null,
        'shortEndInt'   => !empty($subnet['short_lease_pool_end'])   ? (int)ipToInt($subnet['short_lease_pool_end'])   : null,
        'reservedIps'   => $subnet['reserved_ips'] ?? '',
        'addUrl'        => 'reservation_add.php?subnet_id=' . (int)$subnet['id'],
    ];
}
