<?php

session_start();
header("Content-Type: application/json");

if(!isset($_SESSION['userid'])){
    exit(json_encode([
        "html"=>"<tr><td colspan='8' class='text-center text-danger'>Unauthorized</td></tr>",
        "totalPage"=>1,
        "currentPage"=>1
    ]));
}

require(realpath(__DIR__ . '/../../services/Model.php'));
$obj = new Model();

/*
|--------------------------------------------------------------------------
| LOAD CACHE + TELNET DATA

|--------------------------------------------------------------------------
*/

$cacheDir = __DIR__ . '/cache';
$cacheOnu = $cacheDir . '/onu_cache.txt';
$cacheAllMac = $cacheDir . '/mac_all.txt';
$cacheMikrotik = $cacheDir . '/mikrotik_cache.json';

$onuCacheTime = 30;
$macCacheTime = 60;
$mikrotikCacheTime = 15;

if (!file_exists($cacheDir)) {
    mkdir($cacheDir, 0777, true);
}



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

$cacheDir = __DIR__.'/cache';

if(!file_exists($cacheDir)){
    mkdir($cacheDir,0777,true);
}

$onuCacheFile = $cacheDir.'/onu_cache.txt';
$mikrotikCacheFile = $cacheDir.'/mikrotik_cache.json';

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

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

/*
|--------------------------------------------------------------------------
| TELNET EXEC
|--------------------------------------------------------------------------
*/

function runTelnetCommand($command){

    global $oltIp,$port,$username,$password,$enablePassword;

    $script = "/usr/bin/expect -c '
    spawn telnet $oltIp $port
    expect \"Username:\"
    send \"$username\r\"
    expect \"Password:\"
    send \"$password\r\"
    expect \">\"
    send \"enable\r\"
    expect \"Password:\"
    send \"$enablePassword\r\"
    expect \"#\"
    send \"$command\r\"
    expect \"#\"
    send \"exit\r\"
    expect eof
    '";

    return shell_exec($script);
}

/*
|--------------------------------------------------------------------------
| PAGE PARAMETER
|--------------------------------------------------------------------------
*/

$page = $_GET['page'] ?? '';
$pg   = max(1,intval($_GET['pg'] ?? 1));

$perPage = 10;

/*
|--------------------------------------------------------------------------
| MAIN LOGIC
|--------------------------------------------------------------------------
*/

if($page === "onu_info"){

/* ===== ONU CACHE ===== */

$cacheTTL = 30;

if(file_exists($onuCacheFile) &&
    (time()-filemtime($onuCacheFile)) < $cacheTTL){

    $onuOutput = file_get_contents($onuCacheFile);

}else{

    $onuOutput = runTelnetCommand("show epon onu-information");
    file_put_contents($onuCacheFile,$onuOutput);
}

/* ===== PARSE ONU ===== */

$allOnu = [];

$lines = explode("\n",$onuOutput);

foreach($lines as $line){

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

        $allOnu[] = [
            "interface"=>$m[1],
            "vendor"=>$m[2],
            "model"=>$m[3],
            "mac"=>formatMac($m[4]),
            "status"=>"UP"
        ];
    }
}

/* ===== MICROTIK CACHE ===== */

$mikrotikCacheTTL = 15;

if(file_exists($mikrotikCacheFile) &&
    (time()-filemtime($mikrotikCacheFile)) < $mikrotikCacheTTL){

    $mikrotikMap = json_decode(file_get_contents($mikrotikCacheFile),true);

}else{

    $mikrotikMap = [];

    $users = $obj->pppeoActiveSecretList(1) ?? [];

    foreach($users as $u){

        if(!empty($u['caller-id'])){

            $mac = formatMac($u['caller-id']);

            $mikrotikMap[$mac] = $u['name'];
        }
    }

    file_put_contents($mikrotikCacheFile,json_encode($mikrotikMap));
}

/* ===== PAGINATION ===== */

$totalPage = max(1,ceil(count($allOnu)/$perPage));

$currentPage = min($pg,$totalPage);

$slice = array_slice(
    $allOnu,
    ($currentPage-1)*$perPage,
    $perPage
);

/* ===== HTML BUILD ===== */

$html = "";

foreach($slice as $o){

    $matchedUser = $mikrotikMap[$o['mac']] ?? null;

    $html .= "<tr>
    <td>{$o['interface']}</td>
    <td>{$o['vendor']}</td>
    <td>{$o['model']}</td>
    <td>{$o['mac']}</td>
    <td><span class='badge bg-success'>UP</span></td>
    <td>".($matchedUser
        ? "<span class='badge bg-success'>Matched</span>"
        : "<span class='badge bg-warning text-dark'>No Client</span>")."</td>
    <td>".($matchedUser ?? "N/A")."</td>
    <td>{$o['mac']}</td>
    </tr>";
}

echo json_encode([
    "html"=>$html,
    "totalPage"=>$totalPage,
    "currentPage"=>$currentPage
]);

exit;
}