<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

// include "../config/connect.php";
// require_once '../config/routeros_api.class.php';

include "/www/wwwroot/bilspro/config/connect.php";
include "/www/wwwroot/bilspro/config/routeros_api.class.php";

$API = new RouterosAPI();
$API->debug = false;

// Konfigurasi MikroTik
$ip       = '103.242.106.56';
$username = 'billdnynet2742';
$password = 'syif@2011@reth@2012';
$port     = '8727';
$board_id = 'S9QL-XRJ5';

// // Konfigurasi MikroTik
// $ip       = '103.26.176.81';
// $username = 'ccnet0304api';
// $password = 'ccnet0304api';
// $port     = '4426';
// $board_id = 'ABMS-YBP77';

if ($API->connect2($ip, $username, $password, $port)) {

    // === PPPoE Active ===
    $pppoe_data = $API->comm("/ppp/active/print");
    $pppoe_active = [];

    foreach ($pppoe_data as $item) {
        $name    = $item['name'] ?? '';
        $address = $item['address'] ?? '';
        if ($name && $address) {
            $pppoe_active[] = "{$name}_{$address}";
        }
    }

    // === Hotspot Users (bukan active) ===
    $hotspot_users = $API->comm("/ip/hotspot/user/print");
    $hotspot_active = [];

    foreach ($hotspot_users as $item) {
        $user    = $item['name'] ?? '';
        $comment = $item['comment'] ?? '';

        if ($user && $comment && strpos($comment, 'Login.') === 0) {
            $clean_comment = substr($comment, strlen('Login.'));
            $hotspot_active[] = "{$user}_{$clean_comment}";
        }
    }

    // === System Resource ===
    $sys = $API->comm("/system/resource/print");
    $board_name = $sys[0]['board-name'] ?? '';
    $uptime     = $sys[0]['uptime'] ?? '';

    $API->disconnect();

    // === Final Output ===
    $response = [
        'pppoe_active'   => implode('|', $pppoe_active),
        'hotspot_active' => implode('|', $hotspot_active),
        'board_name'     => $board_name,
        'uptime'         => $uptime
    ];

    // Pastikan $pdo tersedia
    if (!isset($pdo)) {
        echo json_encode(['status' => 'error', 'message' => 'Koneksi database gagal']);
        exit;
    }

    // Simpan ke DB
    try {
        
        $stmt = $pdo->prepare("UPDATE setting_mikrotik SET pppa = :pppa, hsa = :hsa, uptime = :ut, board_name = :bm, status = 'Connected' WHERE LEFT(board_id, 9) = :id");
        $stmt->execute([
            ':pppa' => $response['pppoe_active'],
            ':hsa' => $response['hotspot_active'],
            ':ut'  => $response['uptime'],
            ':bm'  => $response['board_name'],
            ':id'  => $board_id
        ]);
    } catch (PDOException $e) {
        echo json_encode(['status' => 'error', 'message' => 'DB Error: ' . $e->getMessage()]);
        exit;
    }

    header('Content-Type: application/json');
    // echo json_encode($response, JSON_PRETTY_PRINT);

} else {
    echo json_encode([
        'status' => 'error',
        'message' => 'Tidak dapat terhubung ke RouterOS'
    ]);
}

?>