<?php
declare(strict_types=1);
require_once dirname(__DIR__) . '/_app_guard.php';
app_guard_validate();
require_once dirname(__DIR__) . '/_auth_common.php';
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');
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
    auth_ensure_schema($db);
    $mac = auth_normalize_mac((string)($_POST['mac'] ?? $_GET['mac'] ?? ''));
    $row = [];
    if ($mac !== '') {
        $st = $db->prepare('SELECT * FROM usuarios WHERE mac=? LIMIT 1');
        $st->execute([$mac]);
        $row = $st->fetch(PDO::FETCH_ASSOC) ?: [];
    }
    $branding = auth_branding_payload($db, $row);
    $whatsapp = preg_replace('/\D+/', '', (string)($branding['support_whatsapp'] ?? $branding['whatsapp'] ?? '')) ?: '';
    if ($whatsapp === '') {
        echo json_encode(['status' => 'error', 'message' => 'whatsapp_empty'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        exit;
    }
    $nome = trim((string)($row['nome_cliente'] ?? 'Cliente')) ?: 'Cliente';
    $msg = "Olá, sou {$nome}. Preciso de suporte no aplicativo. MAC: " . ($mac ?: 'não informado');
    echo json_encode([
        'status' => 'success',
        'ok' => true,
        'whatsapp' => $whatsapp,
        'mensagem' => $msg,
        'support_whatsapp' => $whatsapp,
        'qrcode_url' => (string)($branding['qrcode_url'] ?? ''),
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
} catch (Throwable $e) {
    echo json_encode(['status' => 'error', 'message' => 'support_error'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
