<?php

$oltIp = "157.10.28.198";
$port = "2323";
$username = "admin";
$password = "admin";
$enablePassword = "admin";

$command = "show epon onu-information";

/*
|--------------------------------------------------------------------------
| CACHE CONFIG (VERY IMPORTANT FOR PERFORMANCE)
|--------------------------------------------------------------------------
*/

$cacheFile = __DIR__.'/cache/onu_cache.txt';
$cacheTime = 5; // seconds

if(!file_exists(__DIR__.'/cache')){
    mkdir(__DIR__.'/cache', 0777, true);
}

/*
|--------------------------------------------------------------------------
| MAC FORMAT
|--------------------------------------------------------------------------
*/

function formatMac($mac){
    $mac = str_replace('.', '', $mac);
    $mac = strtolower(trim($mac));
    return implode(':', str_split($mac, 2));
}

/*
|--------------------------------------------------------------------------
| OPTIMIZED STREAM PARSER
|--------------------------------------------------------------------------
*/

function parseOnuList($output, $start = 0, $limit = 10){

    if(empty($output)){
        return [];
    }

    $lines = explode("\n", $output);
    $data = [];

    $count = 0;

    foreach($lines as $line){

        if(preg_match('/(EPON\S+)\s+(\S+)\s+(\S+)\s+([0-9A-F\.]+)\s+.*\s+(auto-configured|deregistered)/i', $line, $m)){

            if($count < $start){
                $count++;
                continue;
            }

            if(count($data) >= $limit){
                break;
            }

            $statusRaw = strtolower($m[5]);

            $data[] = [
                "interface" => trim($m[1]),
                "vendor" => trim($m[2]),
                "model" => trim($m[3]),
                "mac" => formatMac($m[4]),
                "status" => ($statusRaw == "auto-configured") ? "UP" : "DOWN"
            ];

            $count++;
        }
    }

    return $data;
}

/*
|--------------------------------------------------------------------------
| EXPECT TELNET SCRIPT
|--------------------------------------------------------------------------
*/

$script = "/usr/bin/expect -c '
set timeout 5

spawn telnet $oltIp $port

expect \"Username:\"
send \"$username\r\"

expect \"Password:\"
send \"$password\r\"

expect \">\"\n
send \"enable\r\"

expect \"Password:\"
send \"$enablePassword\r\"

expect \"#\"\n
send \"$command\r\"

expect \"#\"\n
send \"exit\r\"

expect eof
'";

/*
|--------------------------------------------------------------------------
| GET OLT OUTPUT (CACHE ENABLED)
|--------------------------------------------------------------------------
*/

if(file_exists($cacheFile) && (time() - filemtime($cacheFile)) < $cacheTime){
    $output = file_get_contents($cacheFile);
}else{
    $output = shell_exec($script);
    file_put_contents($cacheFile, $output);
}

/*
|--------------------------------------------------------------------------
| PAGINATION CONFIG
|--------------------------------------------------------------------------
*/

$perPage = 10;

$pageRoute = isset($_GET['page']) ? $_GET['page'] : '';
$currentPage = isset($_GET['pg']) ? intval($_GET['pg']) : 1;

if($pageRoute != "onu_info"){
    $currentPage = 1;
}

$currentPage = max(1, $currentPage);

$start = ($currentPage - 1) * $perPage;

/*
Fast ONU count without parsing full array
*/

$totalData = substr_count($output, "EPON");
$totalPage = ceil($totalData / $perPage);

/*
Parse only required page data
*/

$onus = parseOnuList($output, $start, $perPage);

?>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="refresh" content="30">

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">

<title>ONU Dashboard</title>
</head>

<body>

<div class="container mt-4">

<h4 class="mb-3">ONU Monitoring Dashboard</h4>

<div class="table-responsive">
<table class="table table-bordered table-striped table-hover shadow-sm">

<thead class="table-dark">
<tr>
<th>Interface</th>
<th>Vendor</th>
<th>Model</th>
<th>ONU MAC</th>
<th>Status</th>
</tr>
</thead>

<tbody>

<?php if(!empty($onus)): ?>

<?php foreach($onus as $o): ?>

<tr>
<td><?= htmlspecialchars($o['interface']) ?></td>
<td><?= htmlspecialchars($o['vendor']) ?></td>
<td><?= htmlspecialchars($o['model']) ?></td>
<td><?= htmlspecialchars($o['mac']) ?></td>
<td>
<?php if($o['status'] == "UP"): ?>
<span class="badge bg-success">UP</span>
<?php else: ?>
<span class="badge bg-danger">DOWN</span>
<?php endif; ?>
</td>
</tr>

<?php endforeach; ?>

<?php else: ?>

<tr>
<td colspan="5" class="text-center text-danger">No ONU Found</td>
</tr>

<?php endif; ?>

</tbody>
</table>
</div>

<?php if($totalPage > 1 && $pageRoute=="onu_info"): ?>

<nav>
<ul class="pagination justify-content-center mt-3">

<?php for($i=1; $i<=$totalPage; $i++): ?>

<li class="page-item <?= ($i==$currentPage)?'active':'' ?>">
<a class="page-link" href="?page=onu_info&pg=<?= $i ?>">
<?= $i ?>
</a>
</li>

<?php endfor; ?>

</ul>
</nav>

<?php endif; ?>

</div>

</body>
</html>