<?php
declare(strict_types=1);

require_once dirname(__DIR__) . '/_app_guard.php';
app_guard_validate();
require_once dirname(__DIR__) . '/_auth_common.php';

try {
    $db = new PDO('sqlite:' . dirname(__DIR__) . '/db.db');
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Throwable $e) {
    auth_json_out(['status' => 'error', 'message' => 'db_connection_error']);
}

auth_ensure_schema($db);

$mac = auth_normalize_mac((string)($_REQUEST['mac'] ?? ''));
$dnsList = auth_get_dns_list($db);
$testCfg = auth_get_test_config($db);
$appFlags = auth_get_app_flags($db);
$generalCfg = auth_get_general_app_config($db);
$p2pCfg = auth_get_p2p_node_config($db);
$loginType = strtoupper((string)auth_get_active_login_mode($db));
if (!in_array($loginType, ['MAC', 'USER'], true)) {
    $loginType = ($loginType === 'NORMAL') ? 'USER' : 'MAC';
}

auth_json_out([
    'status' => 'ok',
    'ok' => true,
    'mac' => $mac,
    'dns' => $dnsList,
    'login_type' => $loginType,
    'test_enabled' => (int)($testCfg['enabled'] ?? 0),
    'auto_mac_enabled' => (int)($testCfg['auto_mac_enabled'] ?? 0),
    'test_button_enabled' => (int)($appFlags['test_button_enabled'] ?? 1),
    'qrcode_app_enabled' => (int)($appFlags['qrcode_app_enabled'] ?? 1),
    'renew_button_enabled' => (int)($appFlags['renew_button_enabled'] ?? 1),
    'vencimento_modal_enabled' => (int)($appFlags['vencimento_modal_enabled'] ?? 1),
    'tmdb_api_key' => (string)($generalCfg['tmdb_api_key'] ?? ''),
    'sports_api_url' => (string)($generalCfg['sports_api_url'] ?? ''),
    'app_language' => (string)($generalCfg['app_language'] ?? 'pt_BR'),
    'language_revision' => (string)($generalCfg['language_revision'] ?? ''),
    'p2p_node_url' => (string)($p2pCfg['p2p_node_url'] ?? ''),
    'p2p_node_key' => (string)($p2pCfg['p2p_node_key'] ?? ''),
    'p2p_configured' => !empty($p2pCfg['configured']),
    'p2p_updated_at' => (string)($p2pCfg['p2p_updated_at'] ?? ''),
    'updated_at' => (string)($db->query("SELECT updated_at FROM app_config WHERE id=1 LIMIT 1")->fetchColumn() ?: ''),
]);
