<?php
declare(strict_types=1);

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

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');

function gmm_out(array $p): void { echo json_encode($p, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); exit; }
function gmm_norm_mac(string $mac): string {
    $c = strtoupper(substr(preg_replace('/[^A-Fa-f0-9]/', '', trim($mac)), 0, 12));
    return strlen($c) === 12 ? implode(':', str_split($c, 2)) : '';
}
function gmm_device_type(string $value): string {
    $value = strtolower(trim($value));
    if (in_array($value, ['tv','android_tv','television'], true)) return 'tv';
    if (in_array($value, ['mobile','celular','phone','android','smartphone'], true)) return 'mobile';
    return 'app';
}
function gmm_public_base_url(): string {
    $https = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || (($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https');
    $scheme = $https ? 'https' : 'http';
    $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
    return rtrim($scheme . '://' . $host, '/');
}
function gmm_abs_image_url(string $url): string {
    $url = trim($url);
    if ($url === '') return '';
    if (preg_match('~^https?://~i', $url)) return $url;
    return gmm_public_base_url() . '/' . ltrim($url, '/');
}
function gmm_has_col(PDO $db, string $table, string $col): bool {
    try {
        $st = $db->query("PRAGMA table_info($table)");
        foreach ($st->fetchAll(PDO::FETCH_ASSOC) as $r) if (($r['name'] ?? '') === $col) return true;
    } catch (Throwable $e) {}
    return false;
}
function gmm_ensure_schema(PDO $db): void {
    $db->exec("CREATE TABLE IF NOT EXISTS mac_messages (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        mac TEXT NOT NULL DEFAULT '',
        title TEXT DEFAULT 'Mensagem do servidor',
        message TEXT DEFAULT '',
        image_url TEXT DEFAULT '',
        tempo INTEGER NOT NULL DEFAULT 5,
        active INTEGER NOT NULL DEFAULT 1,
        shown_once INTEGER NOT NULL DEFAULT 0,
        usuario_id INTEGER DEFAULT 0,
        target_all INTEGER NOT NULL DEFAULT 0,
        created_at INTEGER NOT NULL DEFAULT (strftime('%s','now')),
        updated_at INTEGER NOT NULL DEFAULT (strftime('%s','now'))
    )");
    foreach ([
        'image_url' => "TEXT DEFAULT ''",
        'target_all' => "INTEGER NOT NULL DEFAULT 0",
        'shown_once' => "INTEGER NOT NULL DEFAULT 0",
        'updated_at' => "INTEGER NOT NULL DEFAULT (strftime('%s','now'))"
    ] as $c => $sql) {
        if (!gmm_has_col($db, 'mac_messages', $c)) $db->exec("ALTER TABLE mac_messages ADD COLUMN $c $sql");
    }
    $db->exec("CREATE TABLE IF NOT EXISTS mac_message_views (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        message_id INTEGER NOT NULL,
        mac TEXT NOT NULL,
        device_type TEXT NOT NULL DEFAULT 'app',
        message_token TEXT NOT NULL,
        viewed_at INTEGER NOT NULL DEFAULT (strftime('%s','now')),
        UNIQUE(message_id, mac, device_type, message_token)
    )");
    $db->exec("CREATE INDEX IF NOT EXISTS idx_mac_messages_target ON mac_messages(target_all, active, updated_at DESC)");
    $db->exec("CREATE INDEX IF NOT EXISTS idx_mac_message_views_lookup ON mac_message_views(message_id, mac, device_type, message_token)");
}

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);
    gmm_ensure_schema($db);

    $mac = gmm_norm_mac((string)($_POST['mac'] ?? $_GET['mac'] ?? ''));
    if ($mac === '') gmm_out(['status' => 'ok', 'show_message' => false, 'exibir' => false]);

    $device = gmm_device_type((string)($_POST['device_type'] ?? $_GET['device_type'] ?? 'app'));
    $st = $db->prepare("SELECT * FROM mac_messages WHERE active=1 AND (mac=? OR target_all=1 OR mac='*') ORDER BY target_all ASC, updated_at DESC, id DESC LIMIT 1");
    $st->execute([$mac]);
    $m = $st->fetch();
    if (!$m) gmm_out(['status' => 'ok', 'show_message' => false, 'exibir' => false]);

    $token = (string)$m['id'] . ':' . (string)($m['updated_at'] ?? '0');
    $shownOnce = ((int)($m['shown_once'] ?? 1) === 1);

    if ($shownOnce) {
        $v = $db->prepare('SELECT 1 FROM mac_message_views WHERE message_id=? AND mac=? AND device_type=? AND message_token=? LIMIT 1');
        $v->execute([(int)$m['id'], $mac, $device, $token]);
        if ($v->fetch()) gmm_out(['status' => 'ok', 'show_message' => false, 'exibir' => false]);
    }

    gmm_out([
        'status' => 'ok',
        'show_message' => true,
        'exibir' => true,
        'title' => (string)($m['title'] ?: 'Mensagem do servidor'),
        'titulo' => (string)($m['title'] ?: 'Mensagem do servidor'),
        'message' => (string)($m['message'] ?? ''),
        'mensagem' => (string)($m['message'] ?? ''),
        'image_url' => gmm_abs_image_url((string)($m['image_url'] ?? '')),
        'tempo' => max(0, (int)($m['tempo'] ?? 5)),
        'auto_close_seconds' => max(0, (int)($m['tempo'] ?? 5)),
        'message_id' => (int)$m['id'],
        'message_token' => $token,
        'shown_once' => $shownOnce,
        'target_all' => ((int)($m['target_all'] ?? 0) === 1)
    ]);
} catch (Throwable $e) {
    gmm_out(['status' => 'ok', 'show_message' => false, 'exibir' => false]);
}
