<?php
set_time_limit(300);

$id        = $_GET['id'] ?? null;
$vendor    = $_GET['vendor'] ?? null;
$ip        = $_GET['ip'] ?? null;
$community = $_GET['community'] ?? null;

if ($vendor == 1) {
    $oltIp     = $ip;
    $community = $community;

    // OIDs
    $oids = [
        'name'     => '1.3.6.1.2.1.2.2.1.2',                    // ifDescr
        'serial'   => '1.3.6.1.4.1.3320.101.10.1.1.3',
        'vendor'   => '1.3.6.1.4.1.3320.101.10.1.1.1',
        'rx_power' => '1.3.6.1.4.1.3320.101.10.5.1.5',
        'tx_power' => '1.3.6.1.4.1.3320.101.10.5.1.6',
        'distance' => '1.3.6.1.4.1.3320.101.10.1.1.27',
        'download' => '1.3.6.1.2.1.31.1.1.1.10',
        'upload'   => '1.3.6.1.2.1.31.1.1.1.6',
    ];

    function snmpBulkWalk($community, $oltIp, $oids) {
        $community_esc = escapeshellarg($community);
        $ip_esc        = escapeshellarg($oltIp);
        $raw = [];

        foreach ($oids as $key => $oid) {
            $cmd = "snmpbulkwalk -v2c -c $community_esc -Cr400 -t 3 -r 2 $ip_esc $oid 2>&1";
            $output = shell_exec($cmd);
            $lines = explode("\n", trim($output));

            foreach ($lines as $line) {
                $line = trim($line);
                if (empty($line) || stripos($line, 'No Such') !== false || stripos($line, 'Timeout') !== false) continue;

                // Name / STRING
                if (preg_match('/\.(\d+)\s*=\s*STRING:\s*"?(.*?)"?$/', $line, $m)) {
                    $index = $m[1];
                    $raw[$index][$key] = trim($m[2]);
                    continue;
                }

                // Serial Hex
                if (preg_match('/\.(\d+)\s*=\s*Hex-STRING:\s*(.+)/', $line, $m)) {
                    $index = $m[1];
                    $hex = preg_replace('/[^0-9A-Fa-f]/', '', $m[2]);
                    if (strlen($hex) >= 12) {
                        $raw[$index][$key] = strtoupper(implode(':', str_split($hex, 2)));
                    }
                    continue;
                }

                // Vendor STRING
                if (preg_match('/\.(\d+)\s*=\s*STRING:\s*"?(.*?)"?$/', $line, $m)) {
                    $index = $m[1];
                    $raw[$index][$key] = trim($m[2]);
                    continue;
                }

                // Numeric (power, distance, traffic)
                if (preg_match('/\.(\d+)\s*=\s*(INTEGER|Gauge32|Counter64):\s*(\-?\d+)/', $line, $m)) {
                    $index = $m[1];
                    $value = (int)$m[3];
                    if (in_array($key, ['rx_power', 'tx_power'])) {
                        $value = $value / 100; // dBm
                        if (abs($value) > 100) $value = null;
                    }
                    $raw[$index][$key] = $value;
                    continue;
                }
            }
        }

        return $raw;
    }

    // Fetch all raw data
    $rawData = snmpBulkWalk($community, $oltIp, $oids);

    // Step 1: Create serial-based map for power/distance/traffic
    $powerMap = [];
    foreach ($rawData as $idx => $fields) {
        if (!empty($fields['serial']) && strlen($fields['serial']) == 17) {
            $powerMap[$fields['serial']] = [
                'rx_power' => $fields['rx_power'] ?? null,
                'tx_power' => $fields['tx_power'] ?? null,
                'distance' => $fields['distance'] ?? null,
                'download' => $fields['download'] ?? null,
                'upload'   => $fields['upload'] ?? null,
            ];
        }
    }

    // Step 2: Build ONU list from name entries + map using serial
    $onuPorts = [];
    foreach ($rawData as $idx => $fields) {
        if (isset($fields['name']) && preg_match('/^EPON\d+\/\d+[:\.-]\d+$/i', trim($fields['name']))) {
            $serial = $fields['serial'] ?? '-';
            $onu = [
                'name'     => trim($fields['name']),
                'serial'   => $serial,
                'vendor'   => $fields['vendor'] ?? '-',
                'rx_power' => null,
                'tx_power' => null,
                'distance' => null,
                'download' => null,
                'upload'   => null,
            ];

            // Match using serial (this should work now)
            if ($serial !== '-' && isset($powerMap[$serial])) {
                $match = $powerMap[$serial];
                $onu['rx_power'] = $match['rx_power'];
                $onu['tx_power'] = $match['tx_power'];
                $onu['distance'] = $match['distance'];
                $onu['download'] = $match['download'];
                $onu['upload']   = $match['upload'];
            }

            $onuPorts[] = $onu;
        }
    }

    // Sort by interface name
    usort($onuPorts, function ($a, $b) {
        preg_match('/EPON(\d+)\/(\d+)[:\.-](\d+)/i', $a['name'] ?? '', $m1);
        preg_match('/EPON(\d+)\/(\d+)[:\.-](\d+)/i', $b['name'] ?? '', $m2);
        return [(int)($m1[1] ?? 0), (int)($m1[2] ?? 0), (int)($m1[3] ?? 0)]
            <=> [(int)($m2[1] ?? 0), (int)($m2[2] ?? 0), (int)($m2[3] ?? 0)];
    });
?>

<div class="container py-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h5 class="mb-0 text-primary fw-bold">ONU Details</h5>
        <div>
            <span class="badge bg-info text-dark me-3">Total ONUs: <?= count($onuPorts) ?></span>
            <button onclick="location.reload()" class="btn btn-sm btn-outline-primary">🔄 Refresh</button>
        </div>
    </div>

    <div class="table-responsive">
        <table class="table table-bordered table-hover table-striped text-center">
            <thead class="table-primary">
                <tr>
                    <th>SL</th>
                    <th>Interface</th>
                    <th>Serial</th>
                    <th>Vendor</th>
                    <th>Rx Power (dBm)</th>
                    <th>Tx Power (dBm)</th>
                    <th>Distance (m)</th>
                    <th>Download (GB)</th>
                    <th>Upload (GB)</th>
                </tr>
            </thead>
            <tbody>
                <?php $sl = 1; foreach ($onuPorts as $onu): ?>
                    <tr>
                        <td><?= $sl++ ?></td>
                        <td><code><?= htmlspecialchars($onu['name'] ?? '-') ?></code></td>
                        <td><code><?= htmlspecialchars($onu['serial'] ?? '-') ?></code></td>
                        <td><?= htmlspecialchars($onu['vendor'] ?? '-') ?></td>
                        <td>
                            <?php if (isset($onu['rx_power']) && $onu['rx_power'] !== null): ?>
                                <span class="<?= abs($onu['rx_power']) <= 25 ? 'text-success fw-bold' : 'text-danger fw-bold' ?>">
                                    <?= number_format($onu['rx_power'], 2) ?> dBm
                                </span>
                            <?php else: ?>
                                -
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php if (isset($onu['tx_power']) && $onu['tx_power'] !== null): ?>
                                <span class="<?= ($onu['tx_power'] >= -10 && $onu['tx_power'] <= 5) ? 'text-success fw-bold' : 'text-danger fw-bold' ?>">
                                    <?= number_format($onu['tx_power'], 2) ?> dBm
                                </span>
                            <?php else: ?>
                                -
                            <?php endif; ?>
                        </td>
                        <td><?= isset($onu['distance']) && $onu['distance'] > 0 ? $onu['distance'] . ' m' : '-' ?></td>
                        <td><?= isset($onu['download']) && $onu['download'] > 0 ? round($onu['download'] / 1073741824, 2) . ' GB' : '-' ?></td>
                        <td><?= isset($onu['upload']) && $onu['upload'] > 0 ? round($onu['upload'] / 1073741824, 2) . ' GB' : '-' ?></td>
                    </tr>
                <?php endforeach; ?>

                <?php if (empty($onuPorts)): ?>
                    <tr>
                        <td colspan="9" class="text-danger text-center py-4">
                            No ONU data parsed. Check SNMP community, IP, or OLT MIB compatibility.
                        </td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<?php
}else if ($vendor == 2){


    $oltIp = $ip;   
    $community = $community;

    // Needed OIDs
$oids = [
    'name'     => "1.3.6.1.2.1.2.2.1.2",
    'rx_power' => "1.3.6.1.4.1.3320.10.3.4.1.2",
    'tx_power' => "1.3.6.1.4.1.3320.10.3.4.1.3",
    'download' => "1.3.6.1.2.1.31.1.1.1.10", // ifHCInOctets
    'upload'   => "1.3.6.1.2.1.31.1.1.1.6",  // ifHCOutOctets
];

function snmpBulkWalk($community, $oltIp, $oids) {
    $data = [];
    foreach ($oids as $key => $oid) {
        // Fetch SNMP
        $cmd = "snmpbulkwalk -v2c -c $community -Cr400 -t 1 -r 1 $oltIp $oid 2>&1";
        $output = shell_exec($cmd);
        $lines = explode("\n", trim($output));

        foreach ($lines as $line) {
            if (empty($line)) continue;


            if (preg_match('/\.(\d+) = (?:STRING|INTEGER|Hex-STRING|Gauge32|Counter64|): ?"?(.+?)"?$/', $line, $matches)) {
                $index = $matches[1];
                $value = $matches[2];

                // Handle Rx/Tx power
                if (in_array($key, ['rx_power', 'tx_power'])) {
                    $value = (int)$value;
                    if ($value == -65535) $value = 0;
                    $value = $value / 10;
                }

                // Download/Upload in bytes
                if (in_array($key, ['download','upload'])) {
                    $value = (int)$value;
                }

                $data[$index][$key] = $value;
            }
        }
    }
    return $data;
}

$onuData = snmpBulkWalk($community, $oltIp, $oids);

$onuPorts = array_filter($onuData, function ($item) {
    return isset($item['name']) && preg_match('/^GPON\d+\/\d+:\d+$/', $item['name']);
});

uasort($onuPorts, function ($a, $b) {
    preg_match('/GPON(\d+)\/(\d+):(\d+)/', $a['name'], $m1);
    preg_match('/GPON(\d+)\/(\d+):(\d+)/', $b['name'], $m2);
    return [(int)$m1[1], (int)$m1[2], (int)$m1[3]] <=> [(int)$m2[1], (int)$m2[2], (int)$m2[3]];
});
?>

<div class="container py-4">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <span class="badge bg-info text-dark me-3">Total ONUs: <?= count($onuPorts) ?></span>
        <button onclick="location.reload()" class="btn btn-sm btn-outline-primary">🔄 Refresh</button>
    </div>

    <div class="table-responsive">
        <table class="table table-bordered table-hover align-middle">
            <thead class="table-primary text-center">
                <tr>
                    <th scope="col">SL</th>
                    <th scope="col">Interface</th>
                    <th scope="col">Tx Power (dBm)</th>
                    <th scope="col">Rx Power (dBm)</th>
                    <th scope="col">Download (GB)</th>
                    <th scope="col">Upload (GB)</th>
                </tr>
            </thead>
            <tbody class="text-center">
                <?php $sl = 1; ?>
                <?php foreach ($onuPorts as $onu): ?>
                    <tr>
                        <td><?= $sl++ ?></td>
                        <td><?= htmlspecialchars($onu['name'] ?? '-') ?></td>
                        <td><?= isset($onu['tx_power']) ? $onu['tx_power'] . ' dBm' : '0 dBm' ?></td>
                        <td><?= isset($onu['rx_power']) ? $onu['rx_power'] . ' dBm' : '0 dBm' ?></td>
                        <td><?= isset($onu['download']) ? round($onu['download']/1073741824,2).' GB' : '0 GB' ?></td>
                        <td><?= isset($onu['upload']) ? round($onu['upload']/1073741824,2).' GB' : '0 GB' ?></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<?php
}else if($vendor == 3){

$oltIp = $ip;   
$community = $community;

// OIDs
$oidInterface = "1.3.6.1.4.1.37950.1.1.5.12.2.1.14.1.2"; // Interface Name
$oidTxPower = "1.3.6.1.4.1.37950.1.1.5.12.2.1.8.1.6"; // TX
$oidRxPower = "1.3.6.1.4.1.37950.1.1.5.12.2.1.8.1.7"; // RX
$oidDistance = "1.3.6.1.4.1.37950.1.1.5.12.1.12.1.13";

/**
 * SNMP Bulk Walk Helper
 */
function snmpWalkLines($ip, $community, $oid) {
    $cmd = "snmpbulkwalk -v2c -c $community -Cr20 -t 10 -r 5 $ip $oid 2>&1";
    $output = shell_exec($cmd);
    return explode("\n", trim($output));
}

// Fetch TX, RX and Distance
$linesName = snmpWalkLines($oltIp, $community, $oidInterface);
$linesTx = snmpWalkLines($oltIp, $community, $oidTxPower);
$linesRx = snmpWalkLines($oltIp, $community, $oidRxPower);
$linesDist = snmpWalkLines($oltIp, $community, $oidDistance);

    $parsedNames = [];
    foreach ($linesName as $line) {
        if (preg_match('/STRING:\s*"?([^"]*)"?$/', $line, $m)) {
            $parsedNames[] = trim($m[1]);
        } else {
            $parsedNames[] = "-";
        }
    }

    // Custom sort: EPON0/1:1, EPON0/1:2, EPON0/2:1, ...
    usort($parsedNames, function($a, $b) {
        if ($a === "-" || $b === "-") return $a === "-" ? 1 : -1;
        preg_match('/EPON(\d+)\/(\d+):(\d+)/', $a, $ma);
        preg_match('/EPON(\d+)\/(\d+):(\d+)/', $b, $mb);
        if (!$ma || !$mb) return strcmp($a, $b);
        for ($i = 1; $i <= 3; $i++) {
            if ((int)$ma[$i] !== (int)$mb[$i]) {
                return ((int)$ma[$i] < (int)$mb[$i]) ? -1 : 1;
            }
        }
        return 0;
    });

    $linesName = $parsedNames;


    // Parse results
    $interfaces = [];
    $maxCount = max(count($linesName), count($linesTx), count($linesRx), count($linesDist));

    for ($i = 0; $i < $maxCount; $i++) {
        
        $name = isset($linesName[$i]) ? $linesName[$i] : "-";

        // TX Power
        $tx = isset($linesTx[$i]) && preg_match('/STRING:\s*"?([^"]*)"?$/', $linesTx[$i], $mTx) ? trim($mTx[1]) : "-";

        // RX Power
        $rx = isset($linesRx[$i]) && preg_match('/STRING:\s*"?([^"]*)"?$/', $linesRx[$i], $mRx) ? trim($mRx[1]) : "-";

        // Distance
        $dist = isset($linesDist[$i]) && preg_match('/INTEGER:\s*(\d+)/', $linesDist[$i], $mDist) ? trim($mDist[1]) : "-";

        $interfaces[] = [
            'name' => $name,
            'tx'   => $tx,
            'rx'   => $rx,
            'dist' => $dist,
        ];
    }

?>

<!-- === HTML OUTPUT (Bootstrap 5) === -->
<div class="container py-4">
    <div class="card shadow-sm border-0 mb-4">
        <div class="card-body d-flex justify-content-between align-items-center">
            <h5 class="mb-0 text-primary fw-bold">🖧 ONU TX/RX Power & Distance</h5>
            <div>
                <span class="badge bg-info text-dark me-3">
                    Total ONUs: <?= count($interfaces) ?>
                </span>
                <button onclick="location.reload()" class="btn btn-sm btn-outline-primary">
                    🔄 Refresh Data
                </button>
            </div>
        </div>
    </div>

    <div class="card shadow-sm border-0">
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover table-striped table-bordered align-middle mb-0">
                    <thead class="table-primary text-center">
                        <tr>
                            <th>SL</th>
                            <th>ONU Name</th>
                            <th>TX Power</th>
                            <th>RX Power</th>
                            <th>Distance</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php $sl = 1; foreach ($interfaces as $if): ?>
                            <tr class="text-center">
                                <td><?= $sl++ ?></td>
                                <td><code class="fw-medium text-danger"><?= htmlspecialchars($if['name']) ?></code></td>
                                <td><span ><?= htmlspecialchars($if['tx']) ?></span></td>
                                <td><span ><?= htmlspecialchars($if['rx']) ?></span></td>
                                <td><span><?= htmlspecialchars($if['dist']) ?> m</span></td>
                            </tr>
                        <?php endforeach; ?>
                        <?php if (empty($interfaces)): ?>
                            <tr>
                                <td colspan="5" class="text-center text-danger">
                                    No data found.
                                </td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
<?php

}else if($vendor == 4){
    $oltIp = $ip;
    $community = $community;

    // OIDs for interface info, RX & TX power
    $oids = [
        'name'           => "1.3.6.1.2.1.2.2.1.2",        // Interface name
        'download_bytes' => "1.3.6.1.2.1.31.1.1.1.10",   // ifHCInOctets
        'upload_bytes'   => "1.3.6.1.2.1.31.1.1.1.6",    // ifHCOutOctets
        'rx_power'       => "1.3.6.1.4.1.37950.1.1.5.12.2.1.8.1.7", // RX power
        'tx_power'       => "1.3.6.1.4.1.37950.1.1.5.12.2.1.8.1.6", // TX power
    ];

    // Function to run snmpbulkwalk
    function snmpWalkLines($community, $oltIp, $oid) {
        $cmd = "snmpbulkwalk -v2c -c $community $oltIp $oid";
        $output = shell_exec($cmd);
        return explode("\n", trim($output));
    }

    // Step 1: Fetch interface names
    $interfaces = [];
    $lines = snmpWalkLines($community, $oltIp, $oids['name']);
    foreach ($lines as $line) {
        if (preg_match('/\.(\d+) = STRING: "?(.+?)"?$/', $line, $matches)) {
            $interfaces[$matches[1]] = $matches[2]; // key = ifIndex
        }
    }

    // Step 2: Fetch download bytes
    $downloads = [];
    $lines = snmpWalkLines($community, $oltIp, $oids['download_bytes']);
    foreach ($lines as $line) {
        if (preg_match('/\.(\d+) = Counter64: (\d+)/', $line, $matches)) {
            $downloads[$matches[1]] = (int)$matches[2];
        }
    }

    // Step 3: Fetch upload bytes
    $uploads = [];
    $lines = snmpWalkLines($community, $oltIp, $oids['upload_bytes']);
    foreach ($lines as $line) {
        if (preg_match('/\.(\d+) = Counter64: (\d+)/', $line, $matches)) {
            $uploads[$matches[1]] = (int)$matches[2];
        }
    }

    // Step 4: Fetch RX power
    $rxPowers = [];
    $lines = snmpWalkLines($community, $oltIp, $oids['rx_power']);
    foreach ($lines as $line) {
        if (preg_match('/(\d+)\.(\d+) = STRING: "?(.+?)"?$/', $line, $matches)) {
            $ponPort = $matches[1];
            $onuNo   = $matches[2];
            $rxPowers["$ponPort:$onuNo"] = $matches[3]; // e.g., "0.00 mW (-27.96 dBm)"
        }
    }

    // Step 5: Fetch TX power
    $txPowers = [];
    $lines = snmpWalkLines($community, $oltIp, $oids['tx_power']);
    foreach ($lines as $line) {
        if (preg_match('/(\d+)\.(\d+) = STRING: "?(.+?)"?$/', $line, $matches)) {
            $ponPort = $matches[1];
            $onuNo   = $matches[2];
            $txPowers["$ponPort:$onuNo"] = $matches[3]; // e.g., "0.00 mW (-3.00 dBm)"
        }
    }

    // Step 6: Combine data for 4-port & 8-port ONUs
    $onuPorts = [];
foreach ($interfaces as $ifIndex => $name) {
    $name = trim($name);

    // ---- 4-port VSOL (EPON0/1:1)
    if (preg_match('/^EPON\d+\/(\d+):(\d+)$/i', $name, $m)) {
        $ponPort = ltrim($m[1], '0'); // leading zero remove
        $onuNo   = $m[2];
        $key     = "$ponPort:$onuNo"; // match SNMP key format
        $onuPorts[] = [
            'name'           => $name,
            'download_bytes' => $downloads[$ifIndex] ?? null,
            'upload_bytes'   => $uploads[$ifIndex] ?? null,
            'rx_power'       => $rxPowers[$key] ?? null,
            'tx_power'       => $txPowers[$key] ?? null,
        ];
    }

    // ---- 8-port VSOL ONU (EPON01ONU12)
    elseif (preg_match('/^EPON0?(\d+)ONU(\d+)$/i', $name, $m)) {
        $ponPort = ltrim($m[1], '0'); // leading zero remove
        $onuNo   = $m[2];
        $key     = "$ponPort:$onuNo"; // match SNMP key format
        $onuPorts[] = [
            'name'           => $name,
            'download_bytes' => $downloads[$ifIndex] ?? null,
            'upload_bytes'   => $uploads[$ifIndex] ?? null,
            'rx_power'       => $rxPowers[$key] ?? null,
            'tx_power'       => $txPowers[$key] ?? null,
        ];
    }
}

// Step 7: Sort EPON interfaces logically
uasort($onuPorts, function ($a, $b) {
    preg_match('/EPON0?(\d+)\/(\d+):(\d+)/', $a['name'], $m1);
    preg_match('/EPON0?(\d+)\/(\d+):(\d+)/', $b['name'], $m2);
    if ($m1 && $m2) {
        return [$m1[1], $m1[2], $m1[3]] <=> [$m2[1], $m2[2], $m2[3]];
    }
    return strcmp($a['name'], $b['name']);
});
?>
<div class="container py-4">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <span class="badge bg-info text-dark me-3">Total ONUs: <?= count($onuPorts) ?></span>
        <button onclick="location.reload()" class="btn btn-sm btn-outline-primary">🔄 Refresh</button>
    </div>

    <div class="table-responsive">
        <table class="table table-bordered table-hover align-middle">
            <thead class="table-primary text-center">
                <tr>
                    <th scope="col">SL</th>
                    <th scope="col">Interface</th>
                    <th scope="col">Download (GB)</th>
                    <th scope="col">Upload (GB)</th>
                    <th scope="col">RX Power</th>
                    <th scope="col">TX Power</th>
                </tr>
            </thead>
            <tbody class="text-center">
                <?php $sl = 1; ?>
                <?php foreach ($onuPorts as $onu): ?>
                    <tr>
                        <td><?= $sl++ ?></td>
                        <td><?= htmlspecialchars($onu['name'] ?? '-') ?></td>
                        <td>
                            <?= isset($onu['download_bytes']) 
                                ? round($onu['download_bytes'] / 1073741824, 2) 
                                : '-' ?>
                        </td>
                        <td>
                            <?= isset($onu['upload_bytes']) 
                                ? round($onu['upload_bytes'] / 1073741824, 2) 
                                : '-' ?>
                        </td>
                        <td><?= htmlspecialchars($onu['rx_power'] ?? '-') ?></td>
                        <td><?= htmlspecialchars($onu['tx_power'] ?? '-') ?></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<?php
}else if ($vendor == 5) {

    $oltIp     = $ip;
    $community = $community;

    /* =========================
       OIDs
    ==========================*/
    $oidMac    = "1.3.6.1.4.1.17409.2.3.4.1.1.7";
    $oidRx     = "1.3.6.1.4.1.17409.2.3.4.1.1.10";
    $oidTx     = "1.3.6.1.4.1.17409.2.3.4.1.1.11";

    function snmpLines($community, $ip, $oid){
        $cmd = "snmpwalk -v2c -c " . escapeshellarg($community) . " $ip $oid 2>&1";
        $output = shell_exec($cmd);
        return explode("\n", trim($output ?? ''));
    }

    $linesMac = snmpLines($community, $oltIp, $oidMac);
    $linesRx  = snmpLines($community, $oltIp, $oidRx);
    $linesTx  = snmpLines($community, $oltIp, $oidTx);

    $onus = [];

    /* =========================
       MAC - প্রাইমারি কী হিসেবে ব্যবহার
    ==========================*/
    foreach ($linesMac as $line) {
        if (preg_match('/\.(\d+)\s+=\s+Hex-STRING:\s+(.+)/', $line, $m)) {
            $index = $m[1];
            $mac_raw = trim($m[2]);

            $mac = preg_replace('/[^0-9A-Fa-f]/', '', $mac_raw);
            $mac = strtoupper(chunk_split($mac, 2, ':'));
            $mac = rtrim($mac, ':');

            if (empty($mac) || strlen($mac) != 17) continue; // খারাপ MAC স্কিপ

            $onus[$index]['mac'] = $mac;
            $onus[$index]['name'] = "ONU-$index";
            $onus[$index]['status'] = 'Offline'; // ডিফল্ট
        } elseif (preg_match('/\.(\d+)\s+=\s+STRING:\s+(.+)/', $line, $m)) {
            // কিছু লাইনে STRING আসতে পারে
            $index = $m[1];
            $mac_raw = trim($m[2]);
            $mac = preg_replace('/[^0-9A-Fa-f]/', '', $mac_raw);
            if (strlen($mac) == 12) {
                $mac = strtoupper(chunk_split($mac, 2, ':'));
                $onus[$index]['mac'] = rtrim($mac, ':');
                $onus[$index]['name'] = "ONU-$index";
                $onus[$index]['status'] = 'Offline';
            }
        }
    }

    /* =========================
       RX Power - স্ট্যাটাস আপডেট (RX আছে মানে Online)
    ==========================*/
    foreach ($linesRx as $line) {
        if (preg_match('/\.(\d+)\s+=\s+STRING:\s*"?(0x[0-9A-Fa-f]+|E6|CS|)"?/', $line, $m)) {
            $index = $m[1];
            if (!isset($onus[$index])) continue;

            $raw = trim($m[2], '"');
            $rx_dbm = null;

            if ($raw == 'E6') $rx_dbm = -25.0;
            elseif ($raw == 'CS') $rx_dbm = -30.0;
            elseif (strpos($raw, '0x') === 0) {
                $hex = substr($raw, 2);
                $int = hexdec($hex);
                if ($int > 0x7FFF) $int -= 0x10000;
                $rx_dbm = $int / 100.0;
            }

            $onus[$index]['rx'] = ($rx_dbm !== null) ? number_format($rx_dbm, 2) . " dBm" : '-';

            // RX আছে মানে Online
            if ($rx_dbm !== null || $raw !== '') {
                $onus[$index]['status'] = 'Online';
            }
        }
    }

    /* =========================
       TX Power
    ==========================*/
    foreach ($linesTx as $line) {
        if (preg_match('/\.(\d+)\s+=\s+STRING:\s*"?(0x[0-9A-Fa-f]+|)"?/', $line, $m)) {
            $index = $m[1];
            if (!isset($onus[$index])) continue;

            $raw = trim($m[2], '"');
            $tx_dbm = null;
            if (strpos($raw, '0x') === 0) {
                $hex = substr($raw, 2);
                $int = hexdec($hex);
                if ($int > 0x7FFF) $int -= 0x10000;
                $tx_dbm = $int / 100.0;
            }
            $onus[$index]['tx'] = ($tx_dbm !== null) ? number_format($tx_dbm, 2) . " dBm" : '-';
        }
    }
?>
    <div class="container py-4">
    <div class="card shadow-sm border-0 mb-4">
        <div class="card-body d-flex justify-content-between align-items-center">
            <h5 class="mb-0 text-primary fw-bold">🖧 ONU Interface List (Name + Status + MAC + RX Power)</h5>
            <button onclick="location.reload()" class="btn btn-sm btn-outline-primary">🔄 Refresh</button>
        </div>
    </div>
    <span class="badge bg-info text-dark mb-3">
        Total ONUs: <?= count($onus) ?>
    </span>

    <div class="table-responsive">
        <table class="table table-bordered table-hover align-middle">
            <thead class="table-primary text-center">
                <tr>
                    <th>SL</th>
                    <th>ONU Index</th>
                    <th>Status</th>
                    <th>RX Power</th>
                    <th>TX Power</th>
                    <th>MAC</th>
                </tr>
            </thead>
            <tbody class="text-center">
            <?php $sl=1; foreach ($onus as $index => $o): ?>
                <tr>
                    <td><?= $sl++ ?></td>
                    <td><?= htmlspecialchars($o['name'] ?? '-') ?></td>
                    <td>
                        <span class="badge <?= ($o['status'] ?? 'Offline') == 'Online' ? 'bg-success' : 'bg-danger' ?>">
                            <?= htmlspecialchars($o['status'] ?? 'Offline') ?>
                        </span>
                    </td>
                    <td><?= htmlspecialchars($o['rx'] ?? '-') ?></td>
                    <td><?= htmlspecialchars($o['tx'] ?? '-') ?></td>
                    <td><code><?= htmlspecialchars($o['mac'] ?? '-') ?></code></td>
                </tr>
            <?php endforeach; ?>
            <?php if (empty($onus)): ?>
                <tr>
                    <td colspan="6" class="text-center text-danger">No valid ONU data found. Check if SNMP is responding correctly.</td>
                </tr>
            <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>
<?php }


else if ($vendor == 7) { // V-SOL GPON OLT

    $oltIp     = $ip;
    $community = $community;

    // ================= OIDs =================
    $oids = [
        'descr'       => "1.3.6.1.2.1.2.2.1.2",
        'oper_status' => "1.3.6.1.2.1.2.2.1.8",
        'last_change' => "1.3.6.1.2.1.2.2.1.9",
        'speed'       => "1.3.6.1.2.1.2.2.1.5",
        'rx'          => "1.3.6.1.2.1.2.2.1.10",
        'tx'          => "1.3.6.1.2.1.2.2.1.16"
    ];

    $onuMacOid     = "1.3.6.1.4.1.37950.1.1.5.10.3.2.1.3";  // Vendor MAC
    $vendorOid     = "1.3.6.1.4.1.37950.1.1.5.10.3.5.1.7";   // Vendor info

    function snmpBulkFetch($community, $oltIp, $oids) {
        $data = [];
        foreach ($oids as $key => $oid) {
            $cmd = "snmpbulkwalk -v2c -c {$community} -t 5 -r 2 {$oltIp} {$oid} 2>&1";
            $lines = explode("\n", trim(shell_exec($cmd)));
            foreach ($lines as $line) {
                if (preg_match('/\.(\d+)\s*=\s*(?:STRING|INTEGER|Timeticks|Gauge32|Counter32):\s*(.+)$/i', trim($line), $m)) {
                    $index = $m[1];
                    $value = trim($m[2], '" ');
                    $data[$index][$key] = preg_replace('/^(STRING|INTEGER|Timeticks|Gauge32|Counter32):\s*/i', '', $value);
                }
            }
        }
        return $data;
    }

    // ================= Fetch standard interface data =================
    $interfaceData = snmpBulkFetch($community, $oltIp, $oids);

    // ================= Fetch ONU MAC =================
    $onuMacList = [];
    $onuMacLines = explode("\n", trim(shell_exec("snmpwalk -v2c -c {$community} -t 10 -r 3 {$oltIp} {$onuMacOid} 2>&1")));
    foreach ($onuMacLines as $line) {
        if (preg_match('/\.(\d+)\s*=\s*Hex-STRING:\s*(.+)/', trim($line), $m)) {
            $onuMacList[$m[1]] = strtoupper(str_replace(' ', ':', trim($m[2])));
        }
    }

    // ================= Fetch Vendor info =================
    $vendorMap = [];
    $vendorLines = explode("\n", trim(shell_exec("snmpwalk -v2c -c {$community} -t 10 -r 3 {$oltIp} {$vendorOid} 2>&1")));
    foreach ($vendorLines as $line) {
        if (preg_match('/\.(\d+)\s*=\s*(.+)/', trim($line), $m)) {
            $vendorMap[$m[1]] = trim($m[2]);
        }
    }

    // ================= Status Map =================
    $statusMap = [
        1 => 'Connected', 2 => 'Down', 3 => 'Testing',
        4 => 'Unknown', 5 => 'Dormant', 6 => 'Not Present',
        7 => 'Lower Layer Down'
    ];

    // ================= Process ONU =================
    $onuPorts = [];
    foreach ($interfaceData as $idx => $item) {
        $name = trim($item['descr'] ?? '');
        if (preg_match('/GPON\d+ONU\d+/i', $name)) {
            $statusRaw = (int)($item['oper_status'] ?? 0);
            $status = $statusMap[$statusRaw] ?? 'Unknown';

            $uptimeSec = 0;
            if (isset($item['last_change']) && preg_match('/\((\d+)\)/', $item['last_change'], $m)) {
                $uptimeSec = (int)$m[1] / 100;
            }
            $d = floor($uptimeSec / 86400);
            $h = floor(($uptimeSec % 86400) / 3600);
            $m2 = floor(($uptimeSec % 3600) / 60);
            $uptimeStr = "{$d}d {$h}h {$m2}m";

            // Speed human readable
            $bps = (int)($item['speed'] ?? 0);
            if ($bps >= 1000000000) $speedDisplay = round($bps / 1000000000,1).' Gbps';
            elseif ($bps >= 1000000) $speedDisplay = round($bps / 1000000,0).' Mbps';
            else $speedDisplay = round($bps / 1000,0).' Kbps';

            $rx = (int)($item['rx'] ?? 0);
            $tx = (int)($item['tx'] ?? 0);

            $onuPorts[$idx] = [
                'name'          => $name,
                'status'        => $status,
                'uptime'        => $uptimeStr,
                'mac_addr'      => $onuMacList[$idx] ?? '-',
                'vendor_info'   => $vendorMap[$idx] ?? '-',
                'speed_display' => $speedDisplay,
                'rx_gb'         => round($rx/(1024**3),2),
                'tx_gb'         => round($tx/(1024**3),2),
                'rx'            => $rx,
                'tx'            => $tx,
                'tx_power'      => '-', // Add OID if available
                'rx_power'      => '-'
            ];
        }
    }

    // ================= Sort by GPON/ONU =================
    uasort($onuPorts, function($a,$b){
        preg_match('/GPON(\d+)ONU(\d+)/i',$a['name'],$x);
        preg_match('/GPON(\d+)ONU(\d+)/i',$b['name'],$y);
        return ($x[1] <=> $y[1]) ?: ($x[2] <=> $y[2]);
    });
?>
<div class="container py-4">
    <div class="card shadow-sm mb-3">
        <div class="card-body d-flex justify-content-between">
            <h5 class="fw-bold text-primary">V-SOL GPON ONU List</h5>
            <span class="badge bg-info">Total ONU: <?= count($onuPorts) ?></span>
        </div>
    </div>
    <div class="card shadow-sm">
        <div class="table-responsive">
            <table class="table table-bordered table-hover text-center">
                <thead class="table-primary">
                    <tr>
                        <th>#</th>
                        <th>Interface</th>
                        <th>Status</th>
                        <th>ONU MAC</th>
                        <th>Vendor Info</th>
                        <th>Port Speed</th>
                        <th>Upload (GB)</th>
                        <th>Download (GB)</th>
                    </tr>
                </thead>
                <tbody>
                <?php $i=1; foreach($onuPorts as $onu): ?>
                    <tr>
                        <td><?= $i++ ?></td>
                        <td><code><?= htmlspecialchars($onu['name']) ?></code></td>
                        <td>
                            <span class="badge <?= $onu['status']=='Connected'?'bg-success':'bg-danger' ?>">
                                <?= $onu['status'] ?>
                            </span>
                        </td>
                        <td><code><?= $onu['mac_addr'] ?></code></td>
                        <td><?= $onu['vendor_info'] ?></td>
                        <td><?= $onu['speed_display'] ?></td>
                        <td><?= $onu['tx_gb'] ?> GB</td>
                        <td><?= $onu['rx_gb'] ?> GB</td>
                    </tr>
                <?php endforeach; ?>
                <?php if(empty($onuPorts)): ?>
                    <tr><td colspan="8" class="text-danger text-center">No ONU found - check SNMP output</td></tr>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>
<?php
}






else{
    echo "Invalid vendor";
}
