<?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
$oidIfDescr      = "1.3.6.1.2.1.2.2.1.2";        // Interface Name
$oidIfOperStatus = "1.3.6.1.2.1.2.2.1.8";        // Operational Status
$oidVendorId     = "1.3.6.1.4.1.3320.101.10.1.1.1"; // Vendor ID
$oidSerial       = "1.3.6.1.4.1.3320.101.10.1.1.3"; // Serial Number
$oidOnuUpTime    = "1.3.6.1.2.1.2.2.1.9";           // Uptime (Timeticks)

// Function to convert Hex-STRING to readable serial
function hexToSerial($hexString) {
    $hexString = preg_replace('/[^0-9A-Fa-f]/', '', $hexString);
    return strtoupper(implode(':', str_split($hexString, 2)));
}

// Function to convert Timeticks to human-readable
function ticksToTime($ticks) {
    $seconds = (int)($ticks / 100);
    $days    = floor($seconds / 86400);
    $hours   = floor(($seconds % 86400) / 3600);
    $minutes = floor(($seconds % 3600) / 60);
    $seconds = $seconds % 60;
    return "{$days}d {$hours}h {$minutes}m";
}

// SNMP fetch all lines
$linesName   = explode("\n", trim(shell_exec("snmpbulkwalk -v2c -c $community -t 2 -r 2 $oltIp $oidIfDescr 2>&1")));
$linesStatus = explode("\n", trim(shell_exec("snmpbulkwalk -v2c -c $community -t 2 -r 2 $oltIp $oidIfOperStatus 2>&1")));
$linesVendor = explode("\n", trim(shell_exec("snmpbulkwalk -v2c -c $community -t 2 -r 2 $oltIp $oidVendorId 2>&1")));
$linesSerial = explode("\n", trim(shell_exec("snmpbulkwalk -v2c -c $community -t 2 -r 2 $oltIp $oidSerial 2>&1")));
$linesUpTime = explode("\n", trim(shell_exec("snmpbulkwalk -v2c -c $community -t 2 -r 2 $oltIp $oidOnuUpTime 2>&1")));

// Parsed Interface Names
$interfaces = [];
foreach ($linesName as $line) {
    if (preg_match('/\.(\d+)\s*=\s*STRING:\s*"?(.*?)"?$/', $line, $m)) {
        $index = $m[1];
        $interfaces[$index]['name'] = $m[2];
    }
}

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

foreach ($linesStatus as $line) {

    // example:
    // iso.3.6.1.2.1.2.2.1.8.102 = INTEGER: 1

    if (preg_match('/\.1\.8\.(\d+)\s+=\s+INTEGER:\s+(\d+)/', $line, $m)) {

        $ifIndex = (int)$m[1];   // 102
        $code    = (int)$m[2];   // 1 or 2

        $interfaces[$ifIndex]['status_code'] = $code;
        $interfaces[$ifIndex]['status'] = ($code === 1) ? 'Up' : 'Down';
    }
}



// Parsed Vendor ID
foreach ($linesVendor as $line) {
    if (preg_match('/\.(\d+)\s*=\s*STRING:\s*"?(.*?)"?$/', $line, $m)) {
        $index = $m[1];
        $interfaces[$index]['vendor_id'] = $m[2];
    }
}

// Parsed Serial Number
foreach ($linesSerial as $line) {
    if (preg_match('/\.(\d+)\s*=\s*Hex-STRING:\s*(.+)/', $line, $m)) {
        $index = $m[1];
        $interfaces[$index]['serial_number'] = hexToSerial($m[2]);
    } elseif (preg_match('/\.(\d+)\s*=\s*STRING:\s*"?(.*?)"?$/', $line, $m)) {
        $index = $m[1];
        $interfaces[$index]['serial_number'] = $m[2];
    }
}

// Parsed Uptime
foreach ($linesUpTime as $line) {
    if (preg_match('/\.(\d+)\s*=\s*Timeticks:\s*\((\d+)\)/', $line, $m)) {
        $index = $m[1];
        $ticks = (int)$m[2];
        $interfaces[$index]['uptime'] = ticksToTime($ticks);
    }
}

// Filter only EPON interfaces
$onuPorts = array_filter($interfaces, fn($d) => isset($d['name']) && preg_match('/^EPON\d+\/\d+[:\.-]\d+$/', $d['name']));

// Sort logically
uasort($onuPorts, function ($a, $b) {
    preg_match('/EPON(\d+)\/(\d+)[:\.-](\d+)/', $a['name'], $aMatch);
    preg_match('/EPON(\d+)\/(\d+)[:\.-](\d+)/', $b['name'], $bMatch);
    return [(int)$aMatch[1], (int)$aMatch[2], (int)$aMatch[3]] <=> [(int)$bMatch[1], (int)$bMatch[2], (int)$bMatch[3]];
});
// echo '<pre>';
// print_r($interfaces[102]);
// exit;
?>

<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">🖧 EPON Ports Full Details</h5>
            <div>
                <span class="badge bg-info text-dark me-3">Total EPON: <?= count($onuPorts) ?></span>
                <button onclick="location.reload()" class="btn btn-sm btn-outline-primary">🔄 Refresh</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>Interface Name</th>
                            <th>Description</th>
                            <th>Status</th>
                            <th>Vendor</th>
                            <th>Serial Number</th>
                            <th>Uptime</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php $sl = 1; foreach ($onuPorts as $onu): ?>

                        <?php
                            $serial = isset($onu['serial_number']) ? trim($onu['serial_number']) : '';

                             $agent = $obj->details_by_cond('re_tbl_agent', "onumac = '$serial'");

                            $customerName = $agent['ag_name'] ?? '-';
                            $customerIp   = $agent['ip']     ?? '-';
                            $agentId      = $agent['ag_id']  ?? '-';
                            $customerId   = $agent['cus_id'] ?? '-';
                        ?>


                            <tr class="text-center">
                                <td><?= $sl++ ?></td>
                                <td><code><?= htmlspecialchars($onu['name']) ?></code></td>


                                <td class="text-center align-middle">
                                    <!-- Customer Name -->
                                    <a href="?page=reseller-customer-ledger&id=<?= urlencode((string)$agentId) ?>" class="text-decoration-none fw-semibold">
                                        <?= htmlspecialchars((string)$customerName, ENT_QUOTES, 'UTF-8') ?>
                                    </a>

                                    <!-- IP -->
                                    <br>
                                    <small class="text-muted d-block mb-1">
                                        <a href="?page=reseller-customer-ledger&id=<?= urlencode((string)$agentId) ?>" class="text-decoration-none">
                                            <?= htmlspecialchars((string)$customerIp, ENT_QUOTES, 'UTF-8') ?>
                                        </a>
                                    </small>

                                    <!-- Button with customerId (cus_id) -->
                                    <?php if (!empty($customerId) && $customerId !== '-'): ?>
                                        <a href="?page=reseller-customer-ledger&id=<?= urlencode((string)$agentId) ?>"
                                        class="btn btn-info btn-sm px-2 py-1 waves-effect waves-light">
                                            View
                                        </a>
                                    <?php else: ?>
                                        <button class="btn btn-secondary btn-sm px-2 py-1" disabled>No Customer</button>
                                    <?php endif; ?>
                                </td>




                                <td>
                                    <?php
                                        $status = $onu['status'] ?? 'Unknown';
                                        $badgeClass = match ($status) {
                                            'Up' => 'bg-success',
                                            'Down' => 'bg-danger',
                                            'Testing' => 'bg-warning text-dark',
                                            'Dormant', 'Lower Layer Down' => 'bg-secondary',
                                            default => 'bg-dark',
                                        };
                                    ?>
                                    <span class="badge <?= $badgeClass ?>"><?= $status ?></span>
                                </td>
                                <td><?= htmlspecialchars($onu['vendor_id'] ?? '-') ?></td>
                                <td><code><?= htmlspecialchars($onu['serial_number'] ?? '-') ?></code></td>
                                <td><?= htmlspecialchars($onu['uptime'] ?? '-') ?></td>
                            </tr>
                        <?php endforeach; ?>
                        <?php if (empty($onuPorts)): ?>
                            <tr>
                                <td colspan="6" class="text-center text-danger">No EPON interfaces found</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
<?php

}else if ($vendor == 2){

$oltIp = $ip;
$community = $community;
// === OIDs ===
$oidIfDescr      = "1.3.6.1.2.1.2.2.1.2";        // Interface Name
$oidIfOperStatus = "1.3.6.1.2.1.2.2.1.8";        // Interface Status (1=Up, 2=Down)
$oidIfUpTime     = "1.3.6.1.2.1.2.2.1.9";        // Uptime (Timeticks)
$oidVendor       = "1.3.6.1.4.1.3320.10.2.6.1.3";  // Vendor info

// === Convert Timeticks to human-readable ===
function ticksToTime($ticks) {
    if (!is_numeric($ticks) || $ticks < 0) {
        return '-';
    }
    $seconds = (int)($ticks / 100);
    $days    = floor($seconds / 86400);
    $hours   = floor(($seconds % 86400) / 3600);
    $minutes = floor(($seconds % 3600) / 60);
    return sprintf("%dd %02dh %02dm", $days, $hours, $minutes);
}

// === Fetch SNMP Data ===
function snmpBulk($oid) {
    global $oltIp, $community;

    return explode("\n", trim(shell_exec("snmpbulkwalk -v2c -c $community -t 2 -r 2 $oltIp $oid 2>&1")));
}

$linesName       = snmpBulk($oidIfDescr);
$linesOperStatus = snmpBulk($oidIfOperStatus);
$linesUpTime     = snmpBulk($oidIfUpTime);
$linesVendor     = snmpBulk($oidVendor);

$interfaces = [];
$ponPortIndexes = [];
$vendors = [];

// === Parse Interface Names ===
foreach ($linesName as $line) {
    if (preg_match('/\.(\d+)\s*=\s*STRING:\s*"?([^"]+)"?/', $line, $m)) {
        $index = (int)$m[1];
        $name  = trim($m[2]);
        $interfaces[$index]['name'] = $name;

        if (preg_match('/^(GPON\d+\/\d+)$/', $name, $ponMatch)) {
            $ponPortIndexes[$ponMatch[0]] = $index;
        }
    }
}

// === Parse Operational Status ===
foreach ($linesOperStatus as $line) {
    if (preg_match('/\.(\d+)\s*=\s*INTEGER:\s*\w*\(?(\d+)\)?/', $line, $m)) {
        $index  = (int)$m[1];
        $status = (int)$m[2];
        $interfaces[$index]['status'] = match ($status) {
            1 => 'Up',
            2 => 'Down',
            default => 'Unknown'
        };
    }
}

// === Parse Uptime ===
foreach ($linesUpTime as $line) {
    if (preg_match('/\.(\d+)\s*=\s*Timeticks:\s*\((\d+)\)/', $line, $m)) {
        $index = (int)$m[1];
        $ticks = (int)$m[2];
        $interfaces[$index]['uptime'] = ticksToTime($ticks);
    }
}

// === Parse Vendor Info ===
foreach ($linesVendor as $line) {
    if (preg_match('/\.(\d+)\.(\d+)\s*=\s*STRING:\s*"([^"]+)"/', $line, $m)) {
        $ponIfIndex = (int)$m[1];
        $onuId      = (int)$m[2];
        $vendorInfo = trim($m[3]);
        $vendors[$ponIfIndex][$onuId] = $vendorInfo;
    }
}

// === Filter Only GPON Interfaces ===
$onuPorts = array_filter($interfaces, fn($d) =>
    isset($d['name']) && preg_match('/^GPON\d+\/\d+[:\.-]\d+$/', $d['name'])
);

// === Sort Logically by GPON Position ===
uasort($onuPorts, function ($a, $b) {
    preg_match('/GPON(\d+)\/(\d+)[:\.-](\d+)/', $a['name'], $aMatch);
    preg_match('/GPON(\d+)\/(\d+)[:\.-](\d+)/', $b['name'], $bMatch);
    return [(int)$aMatch[1], (int)$aMatch[2], (int)$aMatch[3]] <=> [(int)$bMatch[1], (int)$bMatch[2], (int)$bMatch[3]];
});
?>
    <style>
        body { background-color: #f8f9fa; }
        .card { border-radius: 0.75rem; }
        .table-hover tbody tr:hover { background-color: #e9ecef; }
        .table th { font-weight: 600; }
        code { color: #d63384; font-size: 0.9em; }
    </style>

<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">🖧 GPON Ports Full Details</h5>
            <div>
                <span class="badge bg-info text-dark me-3 fs-6">Total GPON: <?= count($onuPorts) ?></span>
                <button onclick="location.reload()" class="btn btn-sm btn-outline-primary">🔄 Refresh</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-dark text-center">
                        <tr>
                            <th>SL</th>
                            <th>Interface Name</th>
                            <th>Description</th>
                            <th>Status</th>
                            <th>Vendor</th>
                            <th>Uptime</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($onuPorts)): ?>
                            <tr>
                                <td colspan="5" class="text-center text-danger fw-bold py-4">No GPON interfaces found</td>
                            </tr>
                        <?php else: ?>
                            <?php $sl = 1; foreach ($onuPorts as $onu): ?>

                        <?php
                            $serial = isset($onu['serial_number']) ? trim($onu['serial_number']) : '';

                            $agent = $obj->details_by_cond('re_tbl_agent', "onumac = '$serial'");

                            $customerName = $agent['ag_name'] ?? '-';
                            $customerIp   = $agent['ip']     ?? '-';
                            $agentId      = $agent['ag_id']  ?? '-';
                            $customerId   = $agent['cus_id'] ?? '-';

                        ?>
                        <tr class="text-center">
                            <td><?= $sl++ ?></td>
                            <td><code><?= htmlspecialchars($onu['name']) ?></code></td>


                            <td class="text-center align-middle">
                                <!-- Customer Name -->
                                <a href="?page=reseller-customer-ledger&id=<?= urlencode((string)$agentId) ?>" class="text-decoration-none fw-semibold">
                                    <?= htmlspecialchars((string)$customerName, ENT_QUOTES, 'UTF-8') ?>
                                </a>

                                <!-- IP -->
                                <br>
                                <small class="text-muted d-block mb-1">
                                    <a href="?page=reseller-customer-ledger&id=<?= urlencode((string)$agentId) ?>" class="text-decoration-none">
                                        <?= htmlspecialchars((string)$customerIp, ENT_QUOTES, 'UTF-8') ?>
                                    </a>
                                </small>

                                <!-- Button with customerId (cus_id) -->
                                <?php if (!empty($customerId) && $customerId !== '-'): ?>
                                    <a href="?page=reseller-customer-ledger&id=<?= urlencode((string)$agentId) ?>"
                                    class="btn btn-info btn-sm px-2 py-1 waves-effect waves-light">
                                        View
                                    </a>
                                <?php else: ?>
                                    <button class="btn btn-secondary btn-sm px-2 py-1" disabled>No Customer</button>
                                <?php endif; ?>
                            </td>

                                    <td>
                                        <?php
                                        $status = $onu['status'] ?? 'Unknown';
                                        $badge = match ($status) {
                                            'Up' => 'success',
                                            'Down' => 'danger',
                                            default => 'secondary'
                                        };
                                        ?>
                                        <span class="badge bg-<?= $badge ?>"><?= $status ?></span>
                                    </td>
                                    <td>
                                        <?php
                                        $vendorDisplay = '-';
                                        if (preg_match('/^(GPON\d+\/\d+)[:\.-](\d+)$/', $onu['name'], $nameParts)) {
                                            $ponName = $nameParts[1];
                                            $onuId   = (int)$nameParts[2];

                                            if (isset($ponPortIndexes[$ponName])) {
                                                $ponIfIndex = $ponPortIndexes[$ponName];

                                                if (isset($vendors[$ponIfIndex][$onuId])) {
                                                    $vendorDisplay = htmlspecialchars($vendors[$ponIfIndex][$onuId]);
                                                }
                                            }
                                        }
                                        echo $vendorDisplay;
                                        ?>
                                    </td>
                                    <td><?= htmlspecialchars($onu['uptime'] ?? '-') ?></td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<?php


}else if ($vendor == 3){

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

// === OIDs ===
$oidIfDescr      = "1.3.6.1.2.1.2.2.1.2"; // Interface Name
$oidIfOperStatus = "1.3.6.1.2.1.2.2.1.8"; // Interface Status (1=up, 2=down)
$oidIfMac        = "1.3.6.1.2.1.2.2.1.6"; // MAC Address
$oidIfLastChange = "1.3.6.1.2.1.2.2.1.9"; // Interface Last Change (Timeticks)

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

// === Fetch Data ===
$linesName       = snmpWalkLines($oltIp, $community, $oidIfDescr);
$linesStatus     = snmpWalkLines($oltIp, $community, $oidIfOperStatus);
$linesMac        = snmpWalkLines($oltIp, $community, $oidIfMac);
$linesLastChange = snmpWalkLines($oltIp, $community, $oidIfLastChange);

$interfaces = [];

// === Parse Interface Names ===
foreach ($linesName as $line) {
    if (preg_match('/\.(\d+)\s*=\s*STRING:\s*"?(.*?)"?$/', $line, $m)) {
        $index = $m[1];
        $interfaces[$index]['name'] = trim($m[2]);
    }
}

// === Parse Interface Status ===
foreach ($linesStatus as $line) {
    if (preg_match('/\.(\d+)\s*=\s*INTEGER:\s*(\d+)/', $line, $m)) {
        $index = $m[1];
        $interfaces[$index]['status'] = ($m[2] == 1) ? 'Up' : 'Down';
    }
}

// === Parse MAC Addresses ===
foreach ($linesMac as $line) {
    if (preg_match('/\.(\d+)\s*=\s*Hex-STRING:\s*(.*)/', $line, $m)) {
        $index = $m[1];
        $hex = trim($m[2]);
        if ($hex) {
            $mac = implode(':', array_map(function($h){ return str_pad($h,2,'0',STR_PAD_LEFT); }, explode(' ', $hex)));
            $interfaces[$index]['mac'] = strtoupper($mac);
        } else {
            $interfaces[$index]['mac'] = 'N/A';
        }
    }
}

// === Parse Last Change / Uptime ===
foreach ($linesLastChange as $line) {
    if (preg_match('/\.(\d+)\s*=\s*Timeticks:\s*\((\d+)\)/', $line, $m)) {
        $index = $m[1];
        $ticks = intval($m[2]); // 1 tick = 1/100 second
        $seconds = intval($ticks / 100);

        $days = floor($seconds / 86400);
        $hours = floor(($seconds % 86400) / 3600);
        $minutes = floor(($seconds % 3600) / 60);
        $secs = $seconds % 60;

        $interfaces[$index]['uptime'] = "{$days}d {$hours}h {$minutes}m {$secs}s";
    }
}

// === Filter + Sort Interfaces ===
$validInterfaces = array_filter($interfaces, function ($d) {
    return isset($d['name']) && preg_match('/(PON|EPON|GE|ONU|GPON|epon|pon|ge|onu)/i', $d['name']);
});

usort($validInterfaces, function ($a, $b) {
    $order = ['PON' => 1, 'EPON' => 1, 'GPON' => 1, 'GE' => 2, 'ONU' => 3];
    preg_match('/(PON|EPON|GPON|GE|ONU)/i', $a['name'], $mA);
    preg_match('/(PON|EPON|GPON|GE|ONU)/i', $b['name'], $mB);
    $typeA = $order[strtoupper($mA[1] ?? '')] ?? 99;
    $typeB = $order[strtoupper($mB[1] ?? '')] ?? 99;
    return $typeA === $typeB ? strnatcmp($a['name'], $b['name']) : $typeA - $typeB;
});
?>

<!-- === HTML OUTPUT === -->
<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">🖧 OLT Interface List</h5>
      <div>
        <span class="badge bg-info text-dark me-3">
          Total Interfaces: <?= count($validInterfaces) ?>
        </span>
        <button onclick="location.reload()" class="btn btn-sm btn-outline-primary">
          🔄 Refresh
        </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>Interface Name</th>
              <th>Description</th>
              <th>Status</th>
              <th>MAC Address</th>
              <th>Up Time</th>
            </tr>
          </thead>
          <tbody>
            <?php $sl = 1; foreach ($validInterfaces as $if): ?>

            <?php
                $serial = isset($if['mac']) ? trim($if['mac']) : '';

                $agent = $obj->details_by_cond('re_tbl_agent', "onumac = '$serial'");

                $customerName = $agent['ag_name'] ?? '-';
                $customerIp   = $agent['ip']     ?? '-';
                $agentId      = $agent['ag_id']  ?? '-';
                $customerId   = $agent['cus_id'] ?? '-';
            ?>

              <tr class="text-center">
                <td><?= $sl++ ?></td>
                <td><code><?= htmlspecialchars($if['name']) ?></code></td>


            <td class="text-center align-middle">
                <!-- Customer Name -->
                <a href="?page=reseller-customer-ledger&id=<?= urlencode((string)$agentId) ?>" class="text-decoration-none fw-semibold">
                    <?= htmlspecialchars((string)$customerName, ENT_QUOTES, 'UTF-8') ?>
                </a>

                <!-- IP -->
                <br>
                <small class="text-muted d-block mb-1">
                    <a href="?page=reseller-customer-ledger&id=<?= urlencode((string)$agentId) ?>" class="text-decoration-none">
                        <?= htmlspecialchars((string)$customerIp, ENT_QUOTES, 'UTF-8') ?>
                    </a>
                </small>

                <!-- Button with customerId (cus_id) -->
                <?php if (!empty($customerId) && $customerId !== '-'): ?>
                    <a href="?page=reseller-customer-ledger&id=<?= urlencode((string)$agentId) ?>"
                    class="btn btn-info btn-sm px-2 py-1 waves-effect waves-light">
                        View
                    </a>
                <?php else: ?>
                    <button class="btn btn-secondary btn-sm px-2 py-1" disabled>No Customer</button>
                <?php endif; ?>
            </td>



                <td>
                  <?php if (!empty($if['status'])): ?>
                    <span class="badge <?= $if['status'] === 'Up' ? 'bg-success' : 'bg-danger' ?>">
                      <?= $if['status'] ?>
                    </span>
                  <?php else: ?>
                    <span class="badge bg-secondary">N/A</span>
                  <?php endif; ?>
                </td>
                <td><code><?= $if['mac'] ?? 'N/A' ?></code></td>
                <td><?= $if['uptime'] ?? 'N/A' ?></td>
              </tr>
            <?php endforeach; ?>
            <?php if (empty($validInterfaces)): ?>
              <tr>
                <td colspan="5" class="text-center text-danger">No interfaces found</td>
              </tr>
            <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>
<?php


}else if ($vendor == 4){
    $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";
    $oidOnuUpTime    = "1.3.6.1.2.1.2.2.1.9";
    $oidMacAddr      = "1.3.6.1.4.1.37950.1.1.5.12.1.12.1.6";

    // MAC Table OID (OLT)
    $oidMacTable     = "1.3.6.1.4.1.37950.1.1.5.12.1.8.1.2"; // উদাহরণ, আপনার OLT অনুযায়ী ঠিক করুন

    // === SNMP Fetch Function ===
    function snmpFetch($oid)
    {
        global $oltIp, $community;
        $cmd = "snmpwalk -v2c -c $community -t 4 -r 1 $oltIp $oid";
        $out = shell_exec($cmd);
        return $out ? explode("\n", trim($out)) : [];
    }

    // === Fetch Data ===
    $descrLines  = snmpFetch($oidIfDescr);
    $statusLines = snmpFetch($oidIfOperStatus);
    $uptimeLines = snmpFetch($oidOnuUpTime);
    $macLines    = snmpFetch($oidMacAddr);
    $macTableLines = snmpFetch($oidMacTable);

    $interfaceData = [];

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

    // --- Interface 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('/\.(\d+) = INTEGER: (?:\w+\()?(\d+)\)?/', $line, $m)) {
            $index = $m[1];
            $statusCode = (int)$m[2];
            $interfaceData[$index]['status'] = $statusMap[$statusCode] ?? 'Unknown';
        }
    }

    // --- Interface Uptime ---
    foreach ($uptimeLines as $line) {
        if (preg_match('/\.(\d+) = Timeticks: \((\d+)\)/', $line, $m)) {
            $sec = (int)$m[2] / 100;
            $days = floor($sec / 86400);
            $hours = floor(($sec % 86400) / 3600);
            $mins = floor(($sec % 3600) / 60);
            $interfaceData[$m[1]]['uptime'] = sprintf("%dd %dh %dm", $days, $hours, $mins);
        }
    }

    // --- Filter only ONUs ---
    $onuPorts = array_filter($interfaceData, function ($d) {
        if (!isset($d['name'])) return false;
        return preg_match('/^EPON\d+\/\d+:\d+$/i', $d['name']) || preg_match('/^EPON\d+ONU\d+/i', $d['name']);
    });

    // --- Sort ONUs ---
    uasort($onuPorts, function ($a, $b) {
        if (preg_match('/EPON(\d+)\/(\d+):(\d+)/i', $a['name'], $x) &&
            preg_match('/EPON(\d+)\/(\d+):(\d+)/i', $b['name'], $y)) {
            return [$x[1], $x[2], $x[3]] <=> [$y[1], $y[2], $y[3]];
        }
        if (preg_match('/EPON(\d+)ONU(\d+)/i', $a['name'], $x) &&
            preg_match('/EPON(\d+)ONU(\d+)/i', $b['name'], $y)) {
            return [$x[1], $x[2]] <=> [$y[1], $y[2]];
        }
        return strcmp($a['name'], $b['name']);
    });

    // --- ONU MAC ---
    $macList = [];
    foreach ($macLines as $line) {
        if (preg_match('/= STRING: "?([0-9A-Fa-f: -]+)"?$/', $line, $m)) {
            $macList[] = trim($m[1]);
        }
    }

    $onuKeys = array_keys($onuPorts);
    foreach ($onuKeys as $i => $key) {
        $onuPorts[$key]['mac_addr'] = $macList[$i] ?? '-';
    }

    // --- MAC Table Mapping ---
    $oltMacMap = [];
    foreach ($macTableLines as $line) {
        // উদাহরণ ফরম্যাট: EPON0/1:1 4C:D7:C8:CE:AD:0E
        if (preg_match('/(EPON[\d\/:]+)\s+([0-9A-Fa-f:]+)/', $line, $m)) {
            $oltMacMap[strtoupper($m[1])][] = strtoupper($m[2]);
        }
    }

    function onuNameToSnmpFormat($name) {
        if (preg_match('/EPON(\d)(\d)ONU(\d+)/i', $name, $m)) {
            return "EPON{$m[1]}/{$m[2]}:{$m[3]}";
        }
        return $name;
    }

    foreach ($onuKeys as $key) {
        $snmpId = strtoupper(onuNameToSnmpFormat($onuPorts[$key]['name']));
        $onuPorts[$key]['mac_table'] = isset($oltMacMap[$snmpId]) ? implode(', ', $oltMacMap[$snmpId]) : 'No';
    }

    // === HTML Output ===
    ?>
    <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 Port Overview</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>

        <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>Interface</th>
                                <th>Description</th>
                                <th>Status</th>
                                <th>MAC Address</th>
                                <th>MAC Table</th>
                                <th>Uptime</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($onuPorts)): ?>
                                <tr><td colspan="7" class="text-center text-danger">⚠ No ONU data found</td></tr>
                            <?php else: $sl=1; foreach ($onuPorts as $onu): ?>
                                <tr class="text-center">
                                    <td><?= $sl++ ?></td>
                                    <td><code><?= htmlspecialchars($onu['name']) ?></code></td>
                                    <td>-</td>
                                    <td><span class="badge <?= match($onu['status'] ?? 'Unknown') {
                                        'Connected' => 'bg-success',
                                        'Down' => 'bg-danger',
                                        'Testing' => 'bg-warning text-dark',
                                        'Dormant','Lower Layer Down' => 'bg-secondary',
                                        default => 'bg-dark',
                                    } ?>"><?= $onu['status'] ?? 'Unknown' ?></span></td>
                                    <td><code><?= $onu['mac_addr'] ?? '-' ?></code></td>
                                    <td><code><?= $onu['mac_table'] ?></code></td>
                                    <td><?= $onu['uptime'] ?? '-' ?></td>
                                </tr>
                            <?php endforeach; endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    <?php
}
elseif ($vendor == 5) {

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

    $interfaces = [];

    /* ===============================
       ECOM / EasyPath EPON OIDs (Updated & Tested)
    ================================*/
    $oidMac = "1.3.6.1.4.1.17409.2.3.4.1.1.7";    // ONU MAC (সফল)
    $oidRx  = "1.3.6.1.4.1.17409.2.3.4.1.1.10";   // RX Optical Power (সফল)

    $linesMac = explode("\n", trim(shell_exec("snmpwalk -v2c -c $community $oltIp $oidMac")));
    $linesRx  = explode("\n", trim(shell_exec("snmpwalk -v2c -c $community $oltIp $oidRx")));

    /* ===============================
       MAC (প্রথমে MAC থেকে ONU তৈরি করা)
    ================================*/
    foreach ($linesMac as $line) {
        if (preg_match('/\.(\d+)\s+=\s+Hex-STRING:\s+(.+)/', $line, $m)) {
            $index = $m[1];
            $mac = trim($m[2]);
            $mac = preg_replace('/[^0-9A-Fa-f]/', '', $mac);
            $mac = strtoupper(chunk_split($mac, 2, ':'));
            $mac = rtrim($mac, ':');

            $interfaces[$index] = [
                'mac' => $mac,
                '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];
            $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;
            }

            if (isset($interfaces[$index])) {
                $interfaces[$index]['rx'] = $rx_dbm;
                // RX আছে + MAC আছে মানে Online
                if ($rx_dbm !== null || !empty($raw)) {
                    $interfaces[$index]['status'] = 'Online';
                }
            }
        }
    }
?>

<!-- ===================== HTML Table ===================== -->
<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>

    <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 Index</th>
                            <th>ONU Interface</th>
                            <th>Description</th>
                            <th>Status</th>
                            <th>MAC</th>
                            <th>RX Power (dBm)</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php $sl=1; foreach ($interfaces ?? [] as $index => $d): ?>
                            <?php
                            $mac = $d['mac'] ?? '-';
                            $rx  = isset($d['rx']) && $d['rx'] !== null ? number_format($d['rx'], 2) . ' dBm' : '-';

                            // RX পাওয়ারের কালার
                            $rx_class = '';
                            if (isset($d['rx']) && $d['rx'] !== null) {
                                if ($d['rx'] > 0) $rx_class = 'text-danger fw-bold'; // Overload
                                elseif ($d['rx'] >= -8 && $d['rx'] <= -24) $rx_class = 'text-success fw-bold'; // Good
                                elseif ($d['rx'] < -24) $rx_class = 'text-warning fw-bold'; // Weak
                            }

                            $agent = $obj->details_by_cond('re_tbl_agent', "onumac = '$mac'");

                            $customerName = $agent['ag_name'] ?? '-';
                            $customerIp   = $agent['ip']     ?? '-';
                            $agentId      = $agent['ag_id']  ?? '-';
                            $customerId   = $agent['cus_id'] ?? '-';
                            ?>
                            <tr class="text-center">
                                <td><?= $sl++ ?></td>
                                <td><code><?= htmlspecialchars($index) ?></code></td>
                                <td><code>ONU-<?= htmlspecialchars($index) ?></code></td>

                                <td class="text-center align-middle">
                                    <!-- Customer Name -->
                                    <a href="?page=reseller-customer-ledger&id=<?= urlencode((string)$agentId) ?>" class="text-decoration-none fw-semibold">
                                        <?= htmlspecialchars((string)$customerName, ENT_QUOTES, 'UTF-8') ?>
                                    </a>

                                    <!-- IP -->
                                    <br>
                                    <small class="text-muted d-block mb-1">
                                        <a href="?page=reseller-customer-ledger&id=<?= urlencode((string)$agentId) ?>" class="text-decoration-none">
                                            <?= htmlspecialchars((string)$customerIp, ENT_QUOTES, 'UTF-8') ?>
                                        </a>
                                    </small>

                                    <!-- View Button -->
                                    <?php if (!empty($customerId) && $customerId !== '-'): ?>
                                        <a href="?page=reseller-customer-ledger&id=<?= urlencode((string)$agentId) ?>"
                                           class="btn btn-info btn-sm px-2 py-1 waves-effect waves-light">
                                            View
                                        </a>
                                    <?php else: ?>
                                        <button class="btn btn-secondary btn-sm px-2 py-1" disabled>No Customer</button>
                                    <?php endif; ?>
                                </td>

                                <td>
                                    <?php
                                    $status = $d['status'] ?? 'Offline';
                                    $badgeClass = match($status) {
                                        'Online' => 'bg-success',
                                        'Offline' => 'bg-danger',
                                        'Testing' => 'bg-warning text-dark',
                                        default => 'bg-secondary'
                                    };
                                    ?>
                                    <span class="badge <?= $badgeClass ?>"><?= htmlspecialchars($status) ?></span>
                                </td>

                                <td><code><?= htmlspecialchars($mac) ?></code></td>
                                <td class="<?= $rx_class ?>"><?= htmlspecialchars($rx) ?></td>
                            </tr>
                        <?php endforeach; ?>

                        <?php if (empty($interfaces)): ?>
                            <tr>
                                <td colspan="7" class="text-center text-danger">No ONU interfaces found. Check SNMP connection.</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
<?php
}
elseif ($vendor == 6) {  // TVS Photon OLT - Q-BRIDGE-MIB ব্যবহার করে

    // IP থেকে পোর্ট সরিয়ে শুধু IP নেয়া
    $host_parts = explode(':', $ip);
    $oltIp      = $host_parts[0];  // শুধু IP (103.138.173.56)
    $snmpPort   = isset($host_parts[1]) ? $host_parts[1] : 50501;  // পোর্ট যদি থাকে তাহলে নেয়া, না থাকলে 50501
    $community  = $community;      // "bsd"

    $interfaces = [];

    // Debug Info
    echo "<pre style='background:#f8f9fa; padding:15px; border:1px solid #ddd; margin-bottom:20px;'>";
    echo "Debug Info:\n";
    echo "Original IP from var: $ip\n";
    echo "Clean OLT IP: $oltIp\n";
    echo "SNMP Port: $snmpPort\n";
    echo "Community: $community\n";
    echo "Full Host for SNMP: $oltIp:$snmpPort\n";
    echo "SNMP Walk Command: snmpwalk -v2c -c $community $oltIp:$snmpPort 1.3.6.1.2.1.17.7.1.2.2.1\n\n";

    // সঠিক হোস্ট দিয়ে walk
    $output = shell_exec("snmpwalk -v2c -c \"$community\" $oltIp:$snmpPort 1.3.6.1.2.1.17.7.1.2.2.1 2>&1");

    echo "Raw SNMP Output:\n" . htmlspecialchars($output) . "\n\n";

    if (empty($output) || strpos($output, 'Timeout') !== false || strpos($output, 'No Such') !== false || strpos($output, 'Unknown host') !== false) {
        echo "Error: SNMP failed.\n";
        echo "Check:\n";
        echo "1. OLT IP সঠিক কি না → $oltIp\n";
        echo "2. Community string → $community\n";
        echo "3. সার্ভার থেকে telnet $oltIp $snmpPort চালিয়ে দেখো (কানেক্ট হয় কি না)\n";
        echo "4. Firewall/UDP পোর্ট 50501 আউটবাউন্ড অ্যালাউ করা আছে কি না\n";
        echo "</pre>";
    } else {
        echo "SNMP Success! Parsing data...\n";

        $lines = explode("\n", trim($output));

        $current_mac = null;

        foreach ($lines as $line) {
            $line = trim($line);

            // MAC Address (Hex-STRING)
            if (preg_match('/^SNMPv2-SMI::mib-2\.17\.7\.1\.2\.2\.1\.1\..* = Hex-STRING: ([\da-fA-F\s]+)/', $line, $m)) {
                $hex = str_replace(' ', '', $m[1]);
                if (strlen($hex) == 12) {
                    $current_mac = strtoupper(chunk_split($hex, 2, ':'));
                    $current_mac = rtrim($current_mac, ':');
                }
            } elseif (preg_match('/^SNMPv2-SMI::mib-2\.17\.7\.1\.2\.2\.1\.1\..* = STRING: "?(.*?)"?$/', $line, $m)) {
                $mac_raw = trim($m[1], '"');
                $hex = preg_replace('/[^0-9A-Fa-f]/', '', $mac_raw);
                if (strlen($hex) == 12) {
                    $current_mac = strtoupper(chunk_split($hex, 2, ':'));
                    $current_mac = rtrim($current_mac, ':');
                }
            }

            // Port
            if ($current_mac && preg_match('/^SNMPv2-SMI::mib-2\.17\.7\.1\.2\.2\.1\.2\..* = INTEGER: (\d+)/', $line, $p)) {
                $port = (int)$p[1];

                if ($port >= 5000 && $port <= 5022) {
                    $interfaces[$current_mac] = [
                        'mac'     => $current_mac,
                        'port'    => $port,
                        'status'  => 'Online',
                        'rx'      => null,
                        'pon'     => ($port >= 5001 && $port <= 5014) ? 'PON' : 'Other'
                    ];
                }
                $current_mac = null;
            }
        }

        echo "Parsed " . count($interfaces) . " ONU(s)\n";
        echo "</pre>";

        // ===================== HTML Table =====================
        ?>
        <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">🖧 TVS Photon OLT - ONU List (MAC + Port + Status)</h5>
                    <button onclick="location.reload()" class="btn btn-sm btn-outline-primary">🔄 Refresh</button>
                </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 Index (MAC)</th>
                                    <th>Port</th>
                                    <th>Description</th>
                                    <th>Status</th>
                                    <th>MAC Address</th>
                                    <th>RX Power (dBm)</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php $sl = 1; foreach ($interfaces as $d): ?>
                                    <?php
                                    $mac      = $d['mac'] ?? '-';
                                    $port     = $d['port'] ?? '-';
                                    $status   = $d['status'] ?? 'Offline';
                                    $pon_hint = $d['pon'] ?? '-';
                                    $rx       = $d['rx'] !== null ? number_format($d['rx'], 2) . ' dBm' : '(SNMP-এ পাওয়া যায়নি)';

                                    $badgeClass = ($status === 'Online') ? 'bg-success' : 'bg-danger';

                                    $agent = $obj->details_by_cond('re_tbl_agent', "onumac = '$mac'");

                                    $customerName = $agent['ag_name'] ?? '-';
                                    $customerIp   = $agent['ip']     ?? '-';
                                    $agentId      = $agent['ag_id']  ?? '-';
                                    $customerId   = $agent['cus_id'] ?? '-';
                                    ?>
                                    <tr class="text-center">
                                        <td><?= $sl++ ?></td>
                                        <td><code><?= htmlspecialchars($mac) ?></code></td>
                                        <td><code><?= htmlspecialchars($port) ?> (<?= $pon_hint ?>)</code></td>

                                        <td class="text-center align-middle">
                                            <a href="?page=reseller-customer-ledger&id=<?= urlencode((string)$agentId) ?>" class="text-decoration-none fw-semibold">
                                                <?= htmlspecialchars((string)$customerName, ENT_QUOTES, 'UTF-8') ?>
                                            </a>
                                            <br>
                                            <small class="text-muted d-block mb-1">
                                                <?= htmlspecialchars((string)$customerIp, ENT_QUOTES, 'UTF-8') ?>
                                            </small>
                                            <?php if (!empty($customerId) && $customerId !== '-'): ?>
                                                <a href="?page=reseller-customer-ledger&id=<?= urlencode((string)$agentId) ?>"
                                                   class="btn btn-info btn-sm px-2 py-1 waves-effect waves-light">
                                                    View
                                                </a>
                                            <?php else: ?>
                                                <button class="btn btn-secondary btn-sm px-2 py-1" disabled>No Customer</button>
                                            <?php endif; ?>
                                        </td>

                                        <td>
                                            <span class="badge <?= $badgeClass ?>"><?= htmlspecialchars($status) ?></span>
                                        </td>

                                        <td><code><?= htmlspecialchars($mac) ?></code></td>
                                        <td class="text-warning"><?= htmlspecialchars($rx) ?></td>
                                    </tr>
                                <?php endforeach; ?>

                                <?php if (empty($interfaces)): ?>
                                    <tr>
                                        <td colspan="7" class="text-center text-danger">
                                            No ONU found. Raw output দেখে চেক করো।
                                        </td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </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";

    // 🔥 V-SOL ONU MAC (Vendor MIB)
    $oidOnuMac         = "1.3.6.1.4.1.37950.1.1.5.10.3.2.1.3";

    // ================= SNMP Helper =================
    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);

    $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";
            }
        }
    }

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

    // ================= Client MAC =================
    $macTable = [];
    foreach ($macFdbLines as $line) {
        if (preg_match('/\.(\d+)\.(\d+\.\d+\.\d+\.\d+\.\d+\.\d+)\s*=\s*INTEGER:\s*(\d+)/', $line, $m)) {
            $octets = explode('.', $m[2]);
            if (count($octets) === 6) {
                $mac = strtoupper(implode(':', array_map(
                    fn($o) => str_pad(dechex($o), 2, '0', STR_PAD_LEFT),
                    $octets
                )));
                $macTable[$m[3]][] = $mac;
            }
        }
    }

    // ================= Merge =================
    foreach ($onuPorts as &$onu) {

                if (preg_match('/ONU(\d+)/i', $onu['name'], $m)) {
                    $onuIndex = (int)$m[1];
                    $onu['mac_addr'] = $onuMacMap[$onuIndex] ?? '-';
                } else {
                    $onu['mac_addr'] = '-';
                }

                $onu['uptime'] = $onu['uptime'] ?? '-';
        }
?>
<!-- ================= HTML ================= -->
<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>Client MACs</th> -->
                        <th>Uptime</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 style="max-width:300px"><?= $onu['mac_table'] ?></td> -->
                        <td><?= $onu['uptime'] ?></td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>
<?php
}


else{
    echo "Invalid vendor";
}
