<?php
declare(strict_types=1);

require_once dirname(__DIR__) . '/_app_guard.php';
require_once dirname(__DIR__, 2) . '/includes/profile_pairing.php';
app_guard_validate();
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');

try {
    $db = new PDO('sqlite:' . dirname(__DIR__) . '/db.db', null, null, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES => false,
    ]);
    $db->exec('PRAGMA busy_timeout = 30000');
    pp_ensure_schema($db);
    $mac = pp_normalize_mac((string)($_GET['mac'] ?? $_POST['mac'] ?? ''));
    if ($mac === '') throw new RuntimeException('mac_invalid');
    $st = $db->prepare('SELECT * FROM usuarios WHERE mac=? LIMIT 1');
    $st->execute([$mac]);
    $row = $st->fetch(PDO::FETCH_ASSOC);
    if (!$row) throw new RuntimeException('user_not_found');
    echo json_encode([
        'status' => 'ok',
        'msg' => 'found',
        'data' => array_merge([
            'username' => (string)($row['username'] ?? ''),
            'nome_cliente' => (string)($row['nome_cliente'] ?? ''),
            'whatsapp' => (string)($row['whatsapp'] ?? ''),
            'mac' => (string)($row['mac'] ?? $mac),
        ], pp_profile_payload($row)),
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
} catch (Throwable $e) {
    $message = $e->getMessage() ?: 'profile_error';
    http_response_code(in_array($message, ['mac_invalid', 'user_not_found'], true) ? 404 : 500);
    echo json_encode(['status' => 'erro', 'msg' => $message], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
