<?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 / 10; // 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>Tx Power (dBm)</th>
                    <th>Rx 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['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>
                            <?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><?= 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 =================
    $oidIfDescr      = "1.3.6.1.2.1.2.2.1.2";
    $oidIfOperStatus = "1.3.6.1.2.1.2.2.1.8";
    $oidIfLastChange = "1.3.6.1.2.1.2.2.1.9";
    $oidDot1qFdbPort = "1.3.6.1.2.1.17.7.1.2.2.1.2";
    $oidOnuMac       = "1.3.6.1.4.1.37950.1.1.5.10.3.2.1.3";

    // New OIDs for traffic and speed
    $oidIfSpeed      = "1.3.6.1.2.1.2.2.1.5";      // Interface speed
    $oidIfInOctets   = "1.3.6.1.2.1.2.2.1.10";     // RX bytes
    $oidIfOutOctets  = "1.3.6.1.2.1.2.2.1.16";     // TX bytes

    // Vendor specific OID
    $oidVendorInfo   = "1.3.6.1.4.1.37950.1.1.5.10.3.5.1.7";

    function snmpFetch($oid) {
        global $oltIp, $community;
        $cmd = sprintf(
            'snmpwalk -v2c -c %s -t 10 -r 3 %s %s 2>&1',
            escapeshellarg($community),
            escapeshellarg($oltIp),
            escapeshellarg($oid)
        );
        $out = shell_exec($cmd);
        return $out ? explode("\n", trim($out)) : [];
    }

    // ================= Fetch SNMP =================
    $descrLines    = snmpFetch($oidIfDescr);
    $statusLines   = snmpFetch($oidIfOperStatus);
    $uptimeLines   = snmpFetch($oidIfLastChange);
    $macFdbLines   = snmpFetch($oidDot1qFdbPort);
    $onuMacLines   = snmpFetch($oidOnuMac);

    $speedLines    = snmpFetch($oidIfSpeed);
    $rxLines       = snmpFetch($oidIfInOctets);
    $txLines       = snmpFetch($oidIfOutOctets);

    // ================= Vendor Info =================
    $vendorLines   = snmpFetch($oidVendorInfo);

    $interfaceData = [];

    // ================= Interface Name =================
    foreach ($descrLines as $line) {
        if (preg_match('/ifDescr\.(\d+)\s*=\s*STRING:\s*(.+)/', $line, $m)) {
            $interfaceData[$m[1]]['name'] = trim($m[2], '" ');
        }
    }

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

    foreach ($statusLines as $line) {
        if (preg_match('/ifOperStatus\.(\d+).*?(\d+)/', $line, $m)) {
            if (isset($interfaceData[$m[1]])) {
                $interfaceData[$m[1]]['status'] =
                    $statusMap[$m[2]] ?? 'Unknown';
            }
        }
    }

    // ================= Uptime =================
    foreach ($uptimeLines as $line) {
        if (preg_match('/ifLastChange\.(\d+).*?\((\d+)\)/', $line, $m)) {
            $sec = ((int)$m[2]) / 100;
            $d = floor($sec / 86400);
            $h = floor(($sec % 86400) / 3600);
            $m2 = floor(($sec % 3600) / 60);
            if (isset($interfaceData[$m[1]])) {
                $interfaceData[$m[1]]['uptime'] = "{$d}d {$h}h {$m2}m";
            }
        }
    }

    // ================= Speed =================
    foreach ($speedLines as $line) {
    if (preg_match('/ifSpeed\.(\d+)\s*=\s*Gauge32:\s*(\d+)/', $line, $m)) {
        $ifIndex = $m[1];
        $bps = (int)$m[2];

        if (isset($interfaceData[$ifIndex])) {
            $interfaceData[$ifIndex]['speed_bps'] = $bps;

            // Convert to human-readable
            if ($bps >= 1000000000) {
                $interfaceData[$ifIndex]['speed_display'] = round($bps / 1000000000, 1) . ' Gbps';
            } elseif ($bps >= 1000000) {
                $interfaceData[$ifIndex]['speed_display'] = round($bps / 1000000, 0) . ' Mbps';
            } else {
                $interfaceData[$ifIndex]['speed_display'] = round($bps / 1000, 0) . ' Kbps';
            }
        }
    }
}

    // ================= RX/TX =================
    foreach ($rxLines as $line) {
        if (preg_match('/ifInOctets\.(\d+)\s*=\s*Counter32:\s*(\d+)/', $line, $m)) {
            $interfaceData[$m[1]]['rx'] = (int)$m[2];
        }
    }
    foreach ($txLines as $line) {
        if (preg_match('/ifOutOctets\.(\d+)\s*=\s*Counter32:\s*(\d+)/', $line, $m)) {
            $interfaceData[$m[1]]['tx'] = (int)$m[2];
        }
    }

    // ================= Vendor Info =================
    $vendorMap = [];
    foreach ($vendorLines as $line) {
        if (preg_match('/\.(\d+)\s*=\s*(.+)/', $line, $m)) {
            $vendorMap[$m[1]] = trim($m[2]);
        }
    }

    // ================= Filter ONU Ports =================
    $onuPorts = array_filter($interfaceData, function ($d) {
        return isset($d['name']) &&
               preg_match('/GPON\d+ONU\d+/i', $d['name']);
    });

    // ================= Sort 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]);
    });

    // ================= ONU MAC =================
    $onuMacMap = [];
    foreach ($onuMacLines as $line) {
        if (preg_match('/\.(\d+)\s*=\s*Hex-STRING:\s*(.+)/', $line, $m)) {
            $mac = strtoupper(str_replace(' ', ':', trim($m[2])));
            $onuMacMap[$m[1]] = $mac;
        }
    }

    // ================= Merge =================
    foreach ($onuPorts as &$onu) {
        if (preg_match('/ONU(\d+)/i', $onu['name'], $m)) {
            $onuIndex = (int)$m[1];
            $onu['mac_addr']   = $onuMacMap[$onuIndex] ?? '-';
            $onu['vendor_info'] = $vendorMap[$onuIndex] ?? '-';
        } else {
            $onu['mac_addr'] = '-';
            $onu['vendor_info'] = '-';
        }
        $onu['uptime'] = $onu['uptime'] ?? '-';
        $onu['speed']  = $onu['speed'] ?? '-';
        $onu['rx']     = $onu['rx'] ?? 0;
        $onu['tx']     = $onu['tx'] ?? 0;
        $onu['rx_gb']  = round($onu['rx'] / (1024 ** 3), 2);
        $onu['tx_gb']  = round($onu['tx'] / (1024 ** 3), 2);
        $onu['tx_power'] = $onu['tx_power'] ?? '-'; // Placeholder
        $onu['rx_power'] = $onu['rx_power'] ?? '-'; // Placeholder
    }

?>
<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>  <!-- changed label -->
                        <th>Tx Power (dBm)</th>
                        <th>Rx Power (dBm)</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><?= $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>
                            <?= isset($onu['speed_display']) ? $onu['speed_display'] : '-' ?>
                        </td>
                        <td><?= $onu['tx_power'] ?></td>
                        <td><?= $onu['rx_power'] ?></td>
                        <td><?= $onu['tx_gb'] ?> GB (cumulative)</td>
                        <td><?= $onu['rx_gb'] ?> GB (cumulative)</td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>
<?php
}








else{
    echo "Invalid vendor";
}
