<?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.';
}

include('./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();
?>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">

<style>
.dns-wrap{
    width:100%;
    max-width:none;
    margin:0;
    padding:0 18px;
}
.dns-card{
    border-radius:18px;
    overflow:hidden;
    width:100%;
    margin-bottom:18px;
}
.dns-header{
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:14px;
    padding:18px 22px;
}
.dns-title{
    display:flex;
    align-items:center;
    gap:14px;
}
.dns-title .ic{
    width:44px;
    height:44px;
    min-width:44px;
    border-radius:14px;
    background:rgba(25,135,84,.10);
    border:1px solid rgba(25,135,84,.20);
    display:flex;
    align-items:center;
    justify-content:center;
}
.dns-title .ic i{
    font-size:24px;
    color:#198754;
}
.dns-title h5{
    margin:0;
    font-weight:900;
}
.dns-title span{
    display:block;
    margin-top:3px;
    font-size:13px;
    color:rgba(255,255,255,.55);
}
.badge-soft{
    display:inline-flex;
    align-items:center;
    gap:7px;
    padding:8px 12px;
    border-radius:999px;
    background:rgba(25,135,84,.10);
    border:1px solid rgba(25,135,84,.20);
    color:#198754;
    font-weight:900;
    white-space:nowrap;
}
.input-radius{
    border-radius:14px !important;
    min-height:48px;
}
.textarea-radius{
    border-radius:14px !important;
}
.save-btn{
    border-radius:14px;
    height:46px;
    font-weight:900;
    padding-left:22px;
    padding-right:22px;
}
.table-card{
    border-radius:18px;
    overflow:hidden;
    width:100%;
}
.table thead th{
    font-weight:900;
    white-space:nowrap;
}
.table td{
    vertical-align:middle;
}
.action-btn{
    border-radius:12px;
    font-weight:800;
    margin:2px 0;
}
.img-link{
    font-weight:900;
    text-decoration:none;
}
.status-on{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    border-radius:999px;
    padding:5px 10px;
    background:rgba(25,135,84,.12);
    color:#198754;
    font-weight:900;
}
.status-off{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    border-radius:999px;
    padding:5px 10px;
    background:rgba(220,53,69,.12);
    color:#dc3545;
    font-weight:900;
}
@media(max-width:575px){
    .dns-wrap{
        padding:0 8px;
    }
    .dns-header{
        align-items:flex-start;
        padding:16px;
    }
    .dns-title .ic{
        width:40px;
        height:40px;
        min-width:40px;
    }
    .dns-title .ic i{
        font-size:22px;
    }
    .dns-title h5{
        font-size:18px;
    }
    .badge-soft{
        padding:7px 10px;
        font-size:12px;
    }
    .save-btn{
        width:100%;
    }
}
</style>

<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" style="font-weight: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" style="font-weight: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" style="font-weight: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" style="font-weight: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" style="font-weight: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" style="font-weight: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" style="font-weight: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" style="font-weight: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" onclick="return confirm('Excluir?')" 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 include('./includes/footer.php'); ?>
