<?php
declare(strict_types=1);

/**
ET-Chat Copyright by SEDesign | ET-Chat v3.x.x Lizenz: CCPL | Autor: Evgeni Tcherkasski (info@s-e-d.de)
ET-Chat_T-FISH-MOD Weiterentwicklungen, Optimierungen und Ergänzungen am Code sind das geistige Eigentum von Tommy (Thomas Kuhn) und Harlekin (Bernd Witte).

Die darauf folgende Optimierungen und Ergänzungen am Code sind das Geistige Eigentum von Powermen (Christian K.)
und wird unter der Namenserweiterung M.C.v.x.x.x. geführt. 
PHP 8/9 Ready, XML Parser, PDO Prepared Statements Get Set sicherheit usw.
 */

$pageTitle = "Broadcast";
$backLink  = './?AdminIndex';
$footerNote = "Diese administratorische Änderung ist sofort aktiv." ?? '';

ob_start();

$csrf = $_SESSION['etchat_' . $this->_prefix . 'csrf_token'] ?? '';
$adminId = (int)($_SESSION['etchat_' . $this->_prefix . 'user_id'] ?? 0);
?>

<div class="admin-box">

    <form method="post">
        <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrf, ENT_QUOTES, 'UTF-8') ?>">

        <table>
            <tr>
                <td colspan="2"><strong>📢 Broadcast Nachrichten</strong></td>
            </tr>

            <tr>
                <td>Broadcast Nachricht:</td>
                <td>
                    <textarea class="text admin-textarea-medium"
                        name="broadcast_message"
                        placeholder="Nachricht an alle User..."></textarea>
                </td>
            </tr>

            <tr>
                <td>Nachrichtentyp:</td>
                <td>

                    <label>
                        <input type="radio" id="message_type_standard" name="message_type" value="standard" checked>
                        💬 Standard-Nachricht (nur online User)
                    </label>

                    <label>
                        <input type="radio" id="message_type_general" name="message_type" value="general">
                        📢 Allgemein-Nachricht (auch für neue User)
                    </label>

                    <label>
                        <input type="radio" id="message_type_welcome" name="message_type" value="welcome">
                        🏠 Willkommensnachricht (nur für neue User)
                    </label>

                    <small>
                        💬 Standard: Nur User die online sind<br>
                        📢 Allgemein: Online + neue User<br>
                        🏠 Willkommen: Nur neue User
                    </small>

                </td>
            </tr>

            <tr>
                <td></td>
                <td>

                    <div class="admin-toolbar">
                        <button type="button" onclick="sendMessageOnly()">💬 Nur Nachricht senden</button>
                        <button type="button" onclick="sendBroadcastHard()">📢 Nachricht + Reload</button>
                        <button type="button" onclick="clearBroadcast()">🗑️ Broadcast löschen</button>
                    </div>

                    <div id="broadcast-info"></div>

                </td>
            </tr>

        </table>

    </form>

</div>

<?php
$extraScripts = <<<JS
<script>

const ADMIN_ID = {$adminId};

function getMessageType() {
    if (document.getElementById('message_type_standard').checked) return 'standard';
    if (document.getElementById('message_type_general').checked) return 'general';
    if (document.getElementById('message_type_welcome').checked) return 'welcome';
    return 'standard';
}

function sendMessageOnly() {
    sendBroadcast(true);
}

function sendBroadcastHard() {
    sendBroadcast(false, true);
}

function sendBroadcast(noReload = false, hardReloadAfter = false) {

    const messageInput = document.querySelector('[name="broadcast_message"]');
    const message = messageInput.value.trim();
    const messageType = getMessageType();
    const infoDiv = document.getElementById('broadcast-info');

    if (!message) {
        alert('Bitte Nachricht eingeben!');
        return;
    }

    infoDiv.innerHTML = '🔄 Sende...';

    fetch('./?Broadcast&function=sendBroadcast', {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: 'message=' + encodeURIComponent(message)
            + '&admin_id=' + ADMIN_ID
            + (noReload ? '&no_reload=1' : '')
            + '&message_type=' + messageType
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            alert('✅ Nachricht gesendet!');
            messageInput.value = '';
            checkBroadcastStatus();
            if (hardReloadAfter) hardReload();
        } else {
            alert('❌ Fehler beim Senden');
        }
    })
    .catch(() => alert('❌ Netzwerkfehler'));
}

function clearBroadcast() {

    if (!confirm('Broadcast wirklich löschen?')) return;

    fetch('./?Broadcast&function=clearBroadcast&admin_id=' + ADMIN_ID)
    .then(r => r.json())
    .then(() => {
        alert('✅ Broadcast gelöscht');
        checkBroadcastStatus();
    });
}

function hardReload() {
    const base = location.pathname + location.search;
    location.href = base + (base.includes("?") ? "&" : "?") + "t=" + Date.now();
}

function updateBroadcastInfo(data) {

    const infoDiv = document.getElementById('broadcast-info');

    if (!data.message) {
        infoDiv.innerHTML = '<span style="color:#666;">ℹ️ Kein aktiver Broadcast</span>';
        return;
    }

	let typeText = '';
	switch (data.message_type) {
		case 'standard':
			typeText = '💬 Standard (nur Online User)';
			break;
		case 'general':
			typeText = '📢 Allgemein (alle + neue User)';
			break;
		case 'welcome':
			typeText = '🏠 Welcome (nur neue User)';
			break;
		default:
			typeText = 'Unbekannt';
	}

	const modeText = data.no_reload
		? '💬 Nur Nachricht'
		: '📢 Nachricht + Reload';

    const msg = data.message.replace(/\\n/g, '<br>');

    infoDiv.innerHTML =
        '<div style="color:#4CAF50;font-weight:bold;margin-bottom:8px;">📢 Aktiver Broadcast</div>' +
		'<div style="margin-bottom:6px;"><strong>Typ:</strong> ' + typeText + '</div>' +
		'<div style="margin-bottom:6px;"><strong>Modus:</strong> ' + modeText + '</div>' +
        '<div style="background:#fff;color:#000;padding:8px;border-radius:4px;margin-bottom:8px;">'
        + msg +
        '</div>' +
        '👥 Gesendet an: ' + (data.target_count || 0) + ' User<br>' +
        '👁️ Gesehen von: ' + (data.seen_count || 0) + ' User<br>' +
        '🌐 Online: ' + (data.current_online_count || 0) + ' User';
}

function checkBroadcastStatus() {

    fetch('./?Broadcast&function=getBroadcastStatus&t=' + Date.now())
    .then(r => r.json())
    .then(data => {
        if (data.hasBroadcast) {
            updateBroadcastInfo(data);
        } else {
            document.getElementById('broadcast-info').innerHTML =
                '<span style="color:#666;">ℹ️ Kein aktiver Broadcast</span>';
        }
    });
}

document.addEventListener('DOMContentLoaded', function() {
    checkBroadcastStatus();
    setInterval(checkBroadcastStatus, 2000);
});

</script>
JS;

$content = ob_get_clean();
include "admin_master_template.php";