<?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', 'active' => false, 'message' => 'db_connection_error']);
}

auth_ensure_schema($db);

$mac = auth_normalize_mac((string)($_REQUEST['mac'] ?? ''));
if ($mac === '' || strlen(str_replace(':', '', $mac)) !== 12) {
    auth_json_out(['status' => 'error', 'active' => false, 'message' => 'mac_required']);
}

$row = auth_ensure_pending_mac($db, $mac, da_normalize_device_type((string)($_REQUEST['device_type'] ?? 'tv')));
$hasCredentials = is_array($row) && auth_user_has_credentials($row);
$status = strtolower((string)($row['status'] ?? ''));

auth_json_out([
    'status' => $hasCredentials ? 'ok' : 'pending',
    'ok' => $hasCredentials,
    'active' => $hasCredentials && !in_array($status, ['bloqueado', 'blocked', 'inativo'], true),
    'mac' => $mac,
    'dns' => rtrim((string)($row['dns'] ?? ''), '/'),
    'username' => (string)($row['username'] ?? ''),
    'password' => (string)($row['password'] ?? ''),
    'vencimento' => (string)($row['vencimento'] ?? ''),
]);
