<?php

class MikrotikService
{
    private $API;

    public function __construct($host, $user, $pass)
    {
        require_once('routeros_api.class.php');

        $this->API = new RouterosAPI();
        $this->API->debug = false;

        if (!$this->API->connect($host, $user, $pass)) {
            throw new Exception("❌ MikroTik connection failed");
        }
    }

    /* =========================
       GET ALL PPP USERS
    ========================== */
    public function getUsers()
    {
        return $this->API->comm("/ppp/secret/print");
    }

    /* =========================
       GET SINGLE USER
    ========================== */
    public function getUser($username)
    {
        $res = $this->API->comm("/ppp/secret/print", [
            "?name" => $username
        ]);

        return $res[0] ?? null;
    }

    /* =========================
       DISABLE USER
    ========================== */
    public function disableUser($username)
    {
        $user = $this->getUser($username);

        if (!$user) return false;

        return $this->API->comm("/ppp/secret/set", [
            ".id" => $user['.id'],
            "disabled" => "yes"
        ]);
    }

    /* =========================
       ENABLE USER
    ========================== */
    public function enableUser($username)
    {
        $user = $this->getUser($username);

        if (!$user) return false;

        return $this->API->comm("/ppp/secret/set", [
            ".id" => $user['.id'],
            "disabled" => "no"
        ]);
    }

    /* =========================
       DISCONNECT ACTIVE USER
    ========================== */
    public function disconnectUser($username)
    {
        $active = $this->API->comm("/ppp/active/print", [
            "?name" => $username
        ]);

        if (!empty($active)) {
            return $this->API->comm("/ppp/active/remove", [
                ".id" => $active[0]['.id']
            ]);
        }

        return false;
    }

    /* =========================
       DISABLE + DISCONNECT (BILLING)
    ========================== */
    public function suspendUser($username)
    {
        $this->disableUser($username);
        $this->disconnectUser($username);
    }

    /* =========================
       REMOVE USER COMPLETELY
    ========================== */
    public function removeUser($username)
    {
        $user = $this->getUser($username);

        if (!$user) return false;

        return $this->API->comm("/ppp/secret/remove", [
            ".id" => $user['.id']
        ]);
    }

    public function __destruct()
    {
        $this->API->disconnect();
    }
}