<?php
declare(strict_types=1);
require_once dirname(__DIR__) . '/_app_guard.php';
app_guard_validate();
header('Content-Type: application/json; charset=utf-8');
function out(array $p): void { echo json_encode($p, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES); exit; }
function 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 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 $scheme.'://'.$host; }
function abs_image_url(string $url): string { $url=trim($url); if($url==='') return ''; if(preg_match('~^https?://~i',$url)) return $url; return rtrim(public_base_url(),'/').'/'.ltrim($url,'/'); }
function col(PDO $db,string $t,string $c): bool { try{$st=$db->query("PRAGMA table_info($t)"); foreach($st->fetchAll(PDO::FETCH_ASSOC) as $r){ if(($r['name']??'')===$c)return true; }}catch(Throwable $e){} return false; }
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);
$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(!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))");
$mac=norm_mac((string)($_POST['mac'] ?? $_GET['mac'] ?? '')); if($mac==='') out(['status'=>'erro','show_message'=>false,'exibir'=>false]);
$device=strtolower(trim((string)($_POST['device_type'] ?? $_GET['device_type'] ?? 'app'))) ?: '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) out(['status'=>'ok','show_message'=>false,'exibir'=>false]);
$token=(string)$m['id'] . ':' . (string)($m['updated_at'] ?? '0');
if((int)($m['shown_once'] ?? 0)===1){ $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()) out(['status'=>'ok','show_message'=>false,'exibir'=>false]); }
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'=>abs_image_url((string)($m['image_url'] ?? '')),'tempo'=>(int)($m['tempo'] ?? 5),'auto_close_seconds'=>(int)($m['tempo'] ?? 5),'message_id'=>(int)$m['id'],'message_token'=>$token,'shown_once'=>((int)($m['shown_once'] ?? 0)===1)]);
}catch(Throwable $e){ out(['status'=>'erro','show_message'=>false,'exibir'=>false]); }
