<?php

$GLOBALS["path"] = "./../";

spl_autoload_register(function($class_name) {
		require_once ($GLOBALS["path"].'class/'.$class_name.'.class.php');
});

class Wunschbox extends DbConectionMaker
{

	public function __construct (){

		parent::__construct();
		
		session_start();

		unset($GLOBALS["path"]);

include 'box_config.php';

try {
    $pdo = new PDO("mysql:host=$dbhost;dbname=$dbname;charset=utf8", $dbuser, $dbpass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    die('<p style="color: red; font-weight: bold;">Datenbankverbindung zur Wunschbox fehlgeschlagen.<br>Bitte überprüfe deine Eingaben in der box_config.php.</p>');
}

$plugin_id = $web_php_id;
$wunschbox_aktiv = false;

try {
    $stmt = $pdo->query("SELECT wunschbox FROM `web_php_plugin_" . $plugin_id . "_radio_sendeplan` LIMIT 1");
    if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $wunschbox_aktiv = ($row['wunschbox'] == 1);
    }
} catch (PDOException $e) {
    // Fehler unterdrückt
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = json_decode(file_get_contents('php://input'), true);

    $wunsch = $data['wunsch'];
    $for_who = $data['for_who'];
    $from = $data['from'];
    $greeting = $data['greeting'];

    $user_id = 1;
    $ip = $_SERVER['REMOTE_ADDR'];
    $suche = 'Chat-Wunsch';
    $datum = time();
    $gesendet = 0;
    $sound_an = 0;
    $user_dj = 0;

    $sql = "
        INSERT INTO web_php_plugin_" . $plugin_id . "_radio_wunschbox_text
        (user_id, ip, suche, datum, wunschtitel, fuer_wen, von_wen, text, gesendet, sound_an, user_dj)
        VALUES
        (:user_id, :ip, :suche, :datum, :wunschtitel, :fuer_wen, :von_wen, :text, :gesendet, :sound_an, :user_dj)
    ";

    $stmt = $pdo->prepare($sql);
    $stmt->execute([
        'user_id' => $user_id,
        'ip' => $ip,
        'suche' => $suche,
        'datum' => $datum,
        'wunschtitel' => $wunsch,
        'fuer_wen' => $for_who,
        'von_wen' => $from,
        'text' => $greeting,
        'gesendet' => $gesendet,
        'sound_an' => $sound_an,
        'user_dj' => $user_dj
    ]);

    exit(json_encode(['success' => true]));
}

if (isset($_GET['delete'])) {
    $deleteId = intval($_GET['delete']);
    $stmt = $pdo->prepare("DELETE FROM web_php_plugin_" . $plugin_id . "_radio_wunschbox_text WHERE id = :id");
    $stmt->execute(['id' => $deleteId]);

    echo "<script>window.location.href='wunschbox.php?djbox';</script>";
    exit;
}

$sql = "SELECT * FROM web_php_plugin_" . $plugin_id . "_radio_wunschbox_text ORDER BY datum DESC";
$stmt = $pdo->query($sql);
$wuensche = $stmt->fetchAll(PDO::FETCH_ASSOC);

if (in_array($_SESSION['etchat_'.$this->_prefix.'user_priv'], ["admin", "mod"])) {

$showDjBox = isset($_GET['djbox']);

		}else{
			header("Location: ../");
		}


$showWunschbox = isset($_GET['wunschbox']);

$style = $_SESSION['etchat_'.$prefix.'style'] ?? 'style_chat';
$css = "../styles/$style/style.css";

?>

<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<title>Wunschbox</title>
<link href="<?php echo htmlspecialchars($css); ?>" rel="stylesheet">
<style>body{text-align:center;background-color:black;}.table{width:70%;margin:0 auto;border-collapse:collapse;display:inline-table}.table tbody tr{border-bottom:1px solid #ddd}.table td{padding:10px}.table td img{border-radius:30px}.table td a{color:#fff}i,strong{padding:5px 0;color:orange}input::placeholder{opacity:.75}</style>
</head>
<body>

<?php if($showWunschbox):?>
	<?php if($wunschbox_aktiv):?>
	<div class="mess_back" style="border-radius: 20px; margin-top: 30px; background-color: #333;">
		<h2 style="margin-left: 20px">Wunschbox</h2>
		<form id="wunschboxForm" style="margin-left: 20px">
			<input type="text" id="wunsch" name="wunsch" placeholder="Interpret - Titel:" required><br><br>
			<input type="text" id="for_who" name="for_who" placeholder="Für:" ><br><br>
			<input type="text" id="from" name="from" placeholder="Von:" required><br><br>
			<input type="text" id="greeting" name="greeting" placeholder="Gruß:" ><br><br>
			<input type="submit" id="submit_button" value="📨 Gruß senden">
		</form>
		<div id="radio_wunschbox"></div>
	</div>
	<?php else:?>
	<div style="margin-top:30px;">
		<img src="ohne-wunschbox.png" alt="Wunschbox geschlossen">
		<p style="color: orange; font-size: 18px;">Die laufende Sendung ist ohne Wunschbox.</p>
	</div>
	<?php endif;?>
<?php endif;?>

<?php if($showDjBox):?>
	<div>
		<?php if(empty($wuensche)):?>
			<div style="text-align: center; color: orange; font-size: 18px; margin-top: 20px;">
				<p>Keine Wünsche vorhanden.</p>
				<img src="sad-emoji.png" alt="Keine WÃ¼nsche" style="width: 200px; height: auto;">
			</div>
		<?php else:?>
			<table class="table">
				<tbody>

<?php foreach ($wuensche as $wunsch):

    // Benutzername aus dem Feld 'von_wen' holen und absichern
    $username = htmlspecialchars($wunsch['von_wen']);

    // Standard-Avatar (wenn kein benutzerspezifischer Avatar gefunden wird)
    $avatar = '../img/noavatar.jpg';

    // Verzeichnis, in dem Avatare gespeichert sind
    $avatarDir = '../avatar/';

    // Mögliche Dateiendungen, die geprüft werden
	$avatar = null;
	foreach (['jpg', 'png', 'gif'] as $ext) {
    	$pattern = $avatarDir . $username . '-*.' . $ext;
	    $matches = glob($pattern);
    	if (!empty($matches)) {
        	$avatar = $matches[0]; // erste passende Datei nehmen
	        break;
    	}
	}
?>

<tr>
	<td style="vertical-align:middle;width:60px;">
		<img src="<?= $avatar ?>" alt="<?= $username ?>" style="float: left; max-width:200px; max-height:200px;">
	</td>
<td style="vertical-align:middle;">
    <strong>👤 von:</strong> <?= htmlspecialchars($wunsch['von_wen']) ?><br>
    <strong>🎯 für:</strong> <?= htmlspecialchars($wunsch['fuer_wen']) ?><br>
    <strong>⏰ Uhrzeit:</strong> <?= date('d.m.Y - H:i', intval($wunsch['datum']) + 3600); ?><br>
    <strong>🎵 Wunschtitel:</strong> <?= htmlspecialchars($wunsch['wunschtitel']) ?><br>
    <strong>💬 Gruß:</strong> <?= htmlspecialchars($wunsch['text']) ?>
</td>
<td style="vertical-align:middle;width:60px;">
    <a href="?djbox&delete=<?= $wunsch['id'] ?>" onclick="return confirm('Diesen Wunsch wirklich löschen?');">
        🗑️
    </a>
</td>
</tr>

					<?php endforeach;?>
				</tbody>
			</table>
		<?php endif;?>
	</div>
<?php endif;?>

<script>
document.getElementById("wunschboxForm")?.addEventListener("submit", function(event) {
	event.preventDefault();
	var data = {
		wunsch: document.getElementById("wunsch").value,
		for_who: document.getElementById("for_who").value,
		from: document.getElementById("from").value,
		greeting: document.getElementById("greeting").value
	};
	fetch("wunschbox.php?wunschbox", {
		method: "POST",
		headers: { "Content-Type": "application/json" },
		body: JSON.stringify(data)
	})
	.then(response => response.text())
	.then(text => {
		console.log("Antwort erhalten:", text);
		try {
			const data = JSON.parse(text);
			alert("Wunsch erfolgreich gesendet!");
			document.getElementById("wunschboxForm").reset();
		} catch (error) {
			console.error("Fehler beim Parsen von JSON:", error);
			alert("Fehler: Serverantwort ist kein gÃ¼ltiges JSON.");
		}
	})
	.catch(error => {
		console.error("Fetch-Fehler:", error);
		alert("Ein Fehler ist aufgetreten. Bitte versuche es spÃ¤ter erneut.");
	});
});
</script>
<?php
  }}
new Wunschbox();
?>
</body>
</html>