<?php
require_once __DIR__ . '/../includes/bootstrap_api.php';
header('Content-Type: text/plain; charset=utf-8');
include(__DIR__ . '/../includes/functions.php');
$res = $db->select('dns', '*', '', '');
$portal = [];
$accounts = 0;

function formatMac($mac, $doubleDecode = false, $removeSubstr = null) {
    $mac = is_string($mac) ? $mac : '';
    if ($doubleDecode) {
        $mac = base64_decode(base64_decode($mac, true) ?: '', true);
    } else {
        $mac = base64_decode($mac, true);
    }

    if ($mac === false || $mac === null) {
        return '';
    }

    if ($removeSubstr) {
        $mac = str_replace($removeSubstr, "", (string)$mac);
    }

    // Mantém somente HEX e pega 12 caracteres (6 pares)
    $hex = preg_replace('/[^0-9a-fA-F]/', '', (string)$mac);
    $hex = substr($hex, 0, 12);
    if (strlen($hex) !== 12) {
        return '';
    }

    return strtoupper(implode(':', str_split($hex, 2)));
}

$mac = $_GET['mac'] ?? '';
$mac = is_string($mac) ? $mac : '';
$macAddress = formatMac($mac, true, "afea");

// Se vier vazio ou inválido, devolve resposta padrão sem warnings
if (empty($macAddress)) {
    $data = ['portals' => [], 'accounts' => 0];
    echo Encryption::run(json_encode($data), "IBO_38");
    exit;
}

$result = $db->select('playlist', '*', 'mac_address = :mac_address', '', [':mac_address' => $macAddress]);

if (!empty($result)) {
    foreach ($result as $row) {
        if (!empty($row['username'])) {
            $accounts = 1;
            break; // Exit the loop as we found a matching account
        }
    }
}

foreach ($res as $row) {
    if (!empty($res)) {
        $portal[] = ['name' => $row['title'], 'url' => $row['url'], 'id' => $row['id']];
    }
}

$data = ['portals' => $portal, "accounts" => $accounts];
echo Encryption::run(json_encode($data), "IBO_38");
?>