<?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']);
}

$deviceType = da_normalize_device_type((string)($_REQUEST['device_type'] ?? 'tv'));
$meta = [
    'nome_cliente' => (string)($_REQUEST['nome_cliente'] ?? ''),
    'whatsapp' => (string)($_REQUEST['whatsapp'] ?? ''),
    'device_name' => (string)($_REQUEST['device_name'] ?? ''),
    'device_brand' => (string)($_REQUEST['device_brand'] ?? ''),
    'device_model' => (string)($_REQUEST['device_model'] ?? ''),
    'android_version' => (string)($_REQUEST['android_version'] ?? ''),
    'app_version' => (string)($_REQUEST['app_version'] ?? ''),
    'android_id' => (string)($_REQUEST['android_id'] ?? ''),
];
$row = auth_upsert_pending_device($db, $mac, $deviceType, $meta, false, 'check_mac');
$hasCredentials = is_array($row) && auth_user_has_credentials($row);
$status = strtolower((string)($row['status'] ?? ''));
$isPending = !$hasCredentials || in_array($status, ['pending','pendente','aguardando','waiting'], true);

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