<?php
require_once __DIR__.'/../includes/config.php';
header('Content-Type: application/json; charset=utf-8');

$db = db();

$client = [
    'username' => trim((string)($_GET['username'] ?? $_POST['username'] ?? '')),
    'password' => trim((string)($_GET['password'] ?? $_POST['password'] ?? '')),
    'android_id' => trim((string)($_GET['android_id'] ?? $_POST['android_id'] ?? $_GET['device_id'] ?? $_POST['device_id'] ?? '')),
    'code' => trim((string)($_GET['code'] ?? $_POST['code'] ?? '')),
    'client_key' => trim((string)($_GET['client_key'] ?? $_POST['client_key'] ?? '')),
];

$whereParts = ["target_type='global'"];
$params = [];
foreach ($client as $key => $value) {
    if ($value !== '') {
        $whereParts[] = "(target_type=:type_$key AND target_value=:value_$key)";
        $params[":type_$key"] = $key;
        $params[":value_$key"] = $value;
    }
}

$sql = "SELECT id,title,message,target_type,position,speed,updated_at,start_at,end_at,repeat_minutes,priority,color
        FROM screen_messages
        WHERE is_active=1
          AND (" . implode(' OR ', $whereParts) . ")
          AND (start_at='' OR start_at IS NULL OR datetime(start_at) <= datetime('now','localtime'))
          AND (end_at='' OR end_at IS NULL OR datetime(end_at) >= datetime('now','localtime'))
        ORDER BY CASE WHEN target_type='global' THEN 0 ELSE 1 END DESC,
                 CASE WHEN priority='urgente' THEN 1 ELSE 0 END DESC,
                 id DESC
        LIMIT 5";
$stmt = $db->prepare($sql);
foreach ($params as $k => $v) $stmt->bindValue($k, $v, SQLITE3_TEXT);
$res = $stmt->execute();

$banner_position = get_setting('banner_position','top');
if (!in_array($banner_position, ['top','center','bottom'], true)) $banner_position = 'top';
$banner_duration = (int)get_setting('banner_duration','12');
if ($banner_duration < 1) $banner_duration = 12;
if ($banner_duration > 300) $banner_duration = 300;

$items = [];
$idsToLog = [];

// Avisos automáticos de vencimento/bloqueio por MAC/Android ID
$device_key_auto = normalize_mac_value($client['android_id'] ?: $client['client_key'] ?: $client['code'] ?: '');
if (function_exists('expiry_auto_messages_for_device') && $device_key_auto !== '') {
    foreach (expiry_auto_messages_for_device($device_key_auto) as $autoMsg) {
        $items[] = $autoMsg;
    }
}

while ($row = $res->fetchArray(SQLITE3_ASSOC)) {
    $id = (int)$row['id'];
    $idsToLog[] = $id;
    $items[] = [
        'id' => $id,
        'title' => (string)$row['title'],
        'message' => (string)$row['message'],
        'target_type' => (string)$row['target_type'],
        'position' => (string)$row['position'],
        'speed' => (int)$row['speed'],
        'repeat_minutes' => (int)($row['repeat_minutes'] ?? 0),
        'priority' => (string)($row['priority'] ?? 'normal'),
        'color' => (string)($row['color'] ?? '#ffffff'),
        'banner_position' => $banner_position,
        'banner_duration' => $banner_duration,
        'start_at' => (string)($row['start_at'] ?? ''),
        'end_at' => (string)($row['end_at'] ?? ''),
        'updated_at' => (string)$row['updated_at'],
    ];
}

$ip = $_SERVER['REMOTE_ADDR'] ?? '';
$ua = substr((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 0, 250);
foreach ($idsToLog as $messageId) {
    $log = $db->prepare('INSERT INTO screen_message_hits(message_id,client_key,username,android_id,code,ip,user_agent) VALUES(:message_id,:client_key,:username,:android_id,:code,:ip,:user_agent)');
    $log->bindValue(':message_id', $messageId, SQLITE3_INTEGER);
    $log->bindValue(':client_key', $client['client_key'], SQLITE3_TEXT);
    $log->bindValue(':username', $client['username'], SQLITE3_TEXT);
    $log->bindValue(':android_id', $client['android_id'], SQLITE3_TEXT);
    $log->bindValue(':code', $client['code'], SQLITE3_TEXT);
    $log->bindValue(':ip', $ip, SQLITE3_TEXT);
    $log->bindValue(':user_agent', $ua, SQLITE3_TEXT);
    $log->execute();
}

echo json_encode([
    'success' => true,
    'has_message' => count($items) > 0,
    'server_time' => date('Y-m-d H:i:s'),
    'banner_position' => $banner_position,
    'banner_duration' => $banner_duration,
    'messages' => $items
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
