<?php

namespace App\Classes\Accounting;



class RadPostAuth extends ActiveServers
{
    public function __construct()
    {
        parent::__construct();
    }

    private function sortByAuthDate(&$arr)
    {
        usort($arr, function ($a, $b) {
            return strtotime($b->authdate) - strtotime($a->authdate);
        });
    }

    public function clearLogs()
    {
        $this->runQuery(function ($db) {
            $db->table('radpostauth')->delete();
        });
    }

    public function getLoginLogsByUsernames($usernames)
    {
        $logs = [];

        $this->runQuery(function ($db) use ($usernames, &$logs) {
            $result = $db->table('radpostauth')
                ->whereIn('username', $usernames)
                ->take(500)
                ->orderBy('authdate', 'desc')
                ->get();

            $logs = array_merge($logs, $result->toArray());
        });

        $this->sortByAuthDate($logs);

        return $logs;
    }

    public function getAllLoginLogs()
    {
        $logs = [];

        $this->runQuery(function ($db) use (&$logs) {
            $result = $db->table('radpostauth')
                ->take(500)
                ->orderBy('authdate', 'desc')
                ->get();

            $logs = array_merge($logs, $result->toArray());
        });

        $this->sortByAuthDate($logs);


        return $logs;
    }


    public function getAccessLogByUsername($username)
    {
        $logs = [];

        $this->runQuery(function ($db) use ($username, &$logs) {

            $result = $db->table('radpostauth')->where('username', $username)->orderBy('authdate', 'DESC')->limit(50)->get();
            $logs = array_merge($logs, $result->toArray());
        });

        $this->sortByAuthDate($logs);


        return $logs;
    }
}
