<?php
$db = new PDO('sqlite:' . __DIR__ . '/../api/db.db');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

function mr_col(PDO $db, string $table, string $col): bool {
    $st = $db->query("PRAGMA table_info($table)");
    foreach ($st->fetchAll(PDO::FETCH_ASSOC) as $r) {
        if (($r['name'] ?? '') === $col) return true;
    }
    return false;
}

function mr_base_url(): string {
    if (!empty($GLOBALS['BASE_URL'])) {
        return rtrim((string)$GLOBALS['BASE_URL'], '/');
    }
    $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 mr_public_image_url(string $relative): string {
    return rtrim(mr_base_url(), '/') . '/' . ltrim($relative, '/');
}

function mr_normalize_image_url(string $url): string {
    $url = trim($url);
    if ($url === '') return '';
    if (preg_match('~^https?://~i', $url)) return $url;
    return mr_public_image_url($url);
}

$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 (!mr_col($db, 'mac_messages', $c)) $db->exec("ALTER TABLE mac_messages ADD COLUMN $c $sql");
}

$db->exec("CREATE INDEX IF NOT EXISTS idx_mac_messages_target ON mac_messages(target_all, active, updated_at DESC)");

$msg = '';

if (isset($_GET['delete'])) {
    $st = $db->prepare('DELETE FROM mac_messages WHERE id=?');
    $st->execute([(int)$_GET['delete']]);
    $msg = 'Mensagem excluída.';
}

if (isset($_GET['toggle'])) {
    $st = $db->prepare("UPDATE mac_messages SET active=CASE WHEN active=1 THEN 0 ELSE 1 END, updated_at=strftime('%s','now') WHERE id=?");
    $st->execute([(int)$_GET['toggle']]);
    $msg = 'Status alterado.';
}

if (($_SERVER['REQUEST_METHOD'] ?? '') === 'POST') {
    $target = (string)($_POST['target'] ?? '*');
    $targetAll = $target === '*';
    $mac = $targetAll ? '*' : $target;
    $imageUrl = mr_normalize_image_url((string)($_POST['image_url'] ?? ''));

    if (!empty($_FILES['image_file']['tmp_name']) && is_uploaded_file($_FILES['image_file']['tmp_name'])) {
        $dir = __DIR__ . '/../api/img/remote_messages';
        if (!is_dir($dir)) @mkdir($dir, 0775, true);
        $ext = strtolower(pathinfo($_FILES['image_file']['name'] ?? 'jpg', PATHINFO_EXTENSION));
        if (!in_array($ext, ['jpg', 'jpeg', 'png', 'webp', 'gif'], true)) $ext = 'jpg';
        $name = 'remote_' . time() . '_' . mt_rand(1000, 9999) . '.' . $ext;
        $dest = $dir . '/' . $name;
        if (@move_uploaded_file($_FILES['image_file']['tmp_name'], $dest)) {
            @chmod($dest, 0644);
            $imageUrl = mr_public_image_url('api/img/remote_messages/' . $name);
        }
    }

    $st = $db->prepare("INSERT INTO mac_messages (mac,title,message,image_url,tempo,active,shown_once,target_all,updated_at) VALUES (?,?,?,?,?,?,?,?,strftime('%s','now'))");
    $st->execute([
        $mac,
        trim((string)($_POST['title'] ?? '')) ?: 'Mensagem do servidor',
        trim((string)($_POST['message'] ?? '')),
        $imageUrl,
        max(0, (int)($_POST['tempo'] ?? 5)),
        (int)($_POST['active'] ?? 1),
        (int)($_POST['shown_once'] ?? 1),
        $targetAll ? 1 : 0
    ]);
    $msg = 'Mensagem salva.';
}

require_once __DIR__ . '/../includes/header.php';

$users = $db->query("SELECT mac, COALESCE(nome_cliente, username, mac) AS nome FROM usuarios WHERE mac IS NOT NULL AND mac<>'' ORDER BY nome COLLATE NOCASE")->fetchAll();
$rows = $db->query("SELECT * FROM mac_messages ORDER BY updated_at DESC, id DESC LIMIT 100")->fetchAll();
?>
<div class="dns-wrap">
    <div class="card radius-10 dns-card">
        <div class="card-header bg-transparent dns-header">
            <div class="dns-title">
                <div class="ic"><i class="bi bi-chat-left-text"></i></div>
                <div>
                    <h5>Mensagem Global</h5>
                    <span>Envie mensagens para todos os clientes ou para um MAC específico</span>
                </div>
            </div>

            <div class="dns-actions">
                <span class="badge-soft"><i class="bi bi-broadcast"></i> Ativo</span>
            </div>
        </div>

        <div class="card-body">
            <?php if($msg): ?>
                <div class="alert alert-success">
                    <?= htmlspecialchars($msg, ENT_QUOTES, 'UTF-8') ?>
                </div>
            <?php endif; ?>

            <form method="post" enctype="multipart/form-data" class="row g-3">
                <div class="col-lg-6 col-md-6 col-12">
                    <label class="form-label fw-900">Cliente</label>
                    <select name="target" class="form-select input-radius">
                        <option value="*">Todos os clientes</option>
                        <?php foreach($users as $u): ?>
                            <option value="<?= htmlspecialchars((string)$u['mac'], ENT_QUOTES, 'UTF-8') ?>">
                                <?= htmlspecialchars((string)$u['nome'], ENT_QUOTES, 'UTF-8') ?> — <?= htmlspecialchars((string)$u['mac'], ENT_QUOTES, 'UTF-8') ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="col-lg-6 col-md-6 col-12">
                    <label class="form-label fw-900">Título</label>
                    <input name="title" class="form-control input-radius" value="Mensagem do servidor">
                </div>

                <div class="col-12">
                    <label class="form-label fw-900">Mensagem</label>
                    <textarea name="message" class="form-control textarea-radius" rows="4"></textarea>
                </div>

                <div class="col-lg-6 col-md-6 col-12">
                    <label class="form-label fw-900">Imagem por URL</label>
                    <input name="image_url" class="form-control input-radius" placeholder="https://site.com/imagem.jpg ou api/img/minha-imagem.jpg">
                </div>

                <div class="col-lg-6 col-md-6 col-12">
                    <label class="form-label fw-900">Upload de imagem</label>
                    <input type="file" name="image_file" class="form-control input-radius" accept="image/*">
                </div>

                <div class="col-lg-4 col-md-4 col-12">
                    <label class="form-label fw-900">Tempo de expiração em segundos</label>
                    <input type="number" name="tempo" class="form-control input-radius" min="0" value="5">
                </div>

                <div class="col-lg-4 col-md-4 col-12">
                    <label class="form-label fw-900">Mostrar apenas uma vez</label>
                    <select name="shown_once" class="form-select input-radius">
                        <option value="1">Sim</option>
                        <option value="0">Não</option>
                    </select>
                </div>

                <div class="col-lg-4 col-md-4 col-12">
                    <label class="form-label fw-900">Ativo</label>
                    <select name="active" class="form-select input-radius">
                        <option value="1">Sim</option>
                        <option value="0">Não</option>
                    </select>
                </div>

                <div class="col-12">
                    <button class="btn btn-success save-btn">
                        <i class="bi bi-send-check"></i> Enviar/Salvar
                    </button>
                </div>
            </form>
        </div>
    </div>

    <div class="card radius-10 table-card">
        <div class="card-header bg-transparent dns-header">
            <div class="dns-title">
                <div class="ic"><i class="bi bi-list-check"></i></div>
                <div>
                    <h5>Mensagens criadas</h5>
                    <span>Últimas 100 mensagens cadastradas</span>
                </div>
            </div>
        </div>

        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-striped align-middle">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Destino</th>
                            <th>Título</th>
                            <th>Imagem</th>
                            <th>Ativo</th>
                            <th>Ações</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach($rows as $r): ?>
                            <tr>
                                <td><?= (int)$r['id'] ?></td>
                                <td><?= !empty($r['target_all']) ? 'Todos' : htmlspecialchars((string)$r['mac'], ENT_QUOTES, 'UTF-8') ?></td>
                                <td><?= htmlspecialchars((string)$r['title'], ENT_QUOTES, 'UTF-8') ?></td>
                                <td>
                                    <?php if(!empty($r['image_url'])): ?>
                                        <a class="img-link" href="<?= htmlspecialchars((string)$r['image_url'], ENT_QUOTES, 'UTF-8') ?>" target="_blank">Ver imagem</a>
                                    <?php else: ?>
                                        -
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php if(!empty($r['active'])): ?>
                                        <span class="status-on">Sim</span>
                                    <?php else: ?>
                                        <span class="status-off">Não</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <a class="btn btn-sm btn-warning action-btn" href="?toggle=<?= (int)$r['id'] ?>">
                                        <i class="bi bi-power"></i> Ativar/desativar
                                    </a>
                                    <a class="btn btn-sm btn-danger action-btn" data-confirm="Excluir esta mensagem?" href="?delete=<?= (int)$r['id'] ?>">
                                        <i class="bi bi-trash"></i> Excluir
                                    </a>
                                </td>
                            </tr>
                        <?php endforeach; ?>

                        <?php if(empty($rows)): ?>
                            <tr>
                                <td colspan="6" class="text-center">Nenhuma mensagem criada.</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<?php require_once __DIR__ . '/../includes/footer.php'; ?>
