<?php
/*
=====================================================
 DataLife Engine - by SoftNews Media Group
-----------------------------------------------------
 https://dle-news.ru/
-----------------------------------------------------
 Copyright (c) 2004-2025 SoftNews Media Group
=====================================================
 This code is protected by copyright
=====================================================
 File: guestbook.php
-----------------------------------------------------
 Use: Guestbook page (public)
=====================================================
*/

if (!defined('DATALIFEENGINE')) {
	header("HTTP/1.1 403 Forbidden");
	header('Location: ../../');
	die("Hacking attempt!");
}

function dle_guestbook_table(): string {
	return PREFIX . '_guestbook';
}

function dle_guestbook_ensure_table(): void {
	global $db;

	$table = dle_guestbook_table();
	$db->query(
		"CREATE TABLE IF NOT EXISTS {$table} (\n"
		. "  id INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,\n"
		. "  user_id INT(11) UNSIGNED NOT NULL DEFAULT 0,\n"
		. "  name VARCHAR(40) NOT NULL,\n"
		. "  website VARCHAR(255) NOT NULL DEFAULT '',\n"
		. "  message MEDIUMTEXT NOT NULL,\n"
		. "  ip VARCHAR(46) NOT NULL DEFAULT '',\n"
		. "  date INT(11) UNSIGNED NOT NULL DEFAULT 0,\n"
		. "  is_register TINYINT(1) UNSIGNED NOT NULL DEFAULT 0,\n"
		. "  user_group SMALLINT(5) UNSIGNED NOT NULL DEFAULT 5,\n"
		. "  PRIMARY KEY (id),\n"
		. "  KEY date (date)\n"
		. ") ENGINE=MyISAM DEFAULT CHARSET=" . COLLATE,
		false,
		false
	);
}

function dle_guestbook_can_delete(): bool {
	global $is_logged, $member_id, $user_group;
	if (!$is_logged) return false;
	if ((string)($member_id['user_group'] ?? '') === '1') return true;
	return !empty($user_group[$member_id['user_group']]['del_allc']);
}

function dle_guestbook_build_antispam_blocks(): array {
	global $db, $config, $member_id, $user_group, $lang;

	$question = '';
	$sec_code = '';
	$recaptcha = '';
	$extra_html = '';

	$show_question = !empty($user_group[$member_id['user_group']]['comments_question']);
	$show_sec_code = false;
	$show_recaptcha = false;

	$disable_comments_captcha = intval($user_group[$member_id['user_group']]['disable_comments_captcha'] ?? 0);
	if ($disable_comments_captcha && intval($member_id['comm_num'] ?? 0) >= $disable_comments_captcha) {
		$show_question = false;
		$user_group[$member_id['user_group']]['captcha'] = false;
		$user_group[$member_id['user_group']]['comments_question'] = false;
	}

	if ($show_question) {
		$q = $db->super_query("SELECT id, question FROM " . PREFIX . "_question ORDER BY RAND() LIMIT 1");
		if (!isset($q['id']) || !isset($q['question']) || !$q['question']) {
			$show_question = false;
		} else {
			$_SESSION['question'] = intval($q['id']);
			$question = htmlspecialchars(stripslashes($q['question']), ENT_QUOTES, 'UTF-8');
		}
	}

	if (!empty($user_group[$member_id['user_group']]['captcha'])) {
		if (!empty($config['allow_recaptcha'])) {
			$show_recaptcha = true;

			$captcha_name = 'g-recaptcha';
			$captcha_url = "https://www.google.com/recaptcha/api.js?hl={$lang['language_code']}";

			if ($config['allow_recaptcha'] == 3) {
				$captcha_name = 'h-captcha';
				$captcha_url = "https://js.hcaptcha.com/1/api.js?hl={$lang['language_code']}";
			}

			if ($config['allow_recaptcha'] == 4) {
				$captcha_name = 'cf-turnstile';
				$captcha_url = 'https://challenges.cloudflare.com/turnstile/v0/api.js?compat=recaptcha';
			}

			if ($config['allow_recaptcha'] == 2) {
				$recaptcha = '';
				$extra_html = "\n<script src=\"https://www.google.com/recaptcha/api.js?render={$config['recaptcha_public_key']}\" async defer></script>\n";
				$extra_html .= "<script>\n";
				$extra_html .= "document.addEventListener('DOMContentLoaded', function () {\n";
				$extra_html .= "  var form = document.getElementById('guestbook-form');\n";
				$extra_html .= "  if (!form || typeof grecaptcha === 'undefined') return;\n";
				$extra_html .= "  form.addEventListener('submit', function (event) {\n";
				$extra_html .= "    if (form.dataset.recaptchaProcessed === '1') return;\n";
				$extra_html .= "    event.preventDefault();\n";
				$extra_html .= "    grecaptcha.execute('{$config['recaptcha_public_key']}', {action: 'guestbook'}).then(function (token) {\n";
				$extra_html .= "      var input = document.getElementById('g-recaptcha-response');\n";
				$extra_html .= "      if (!input) {\n";
				$extra_html .= "        input = document.createElement('input');\n";
				$extra_html .= "        input.type = 'hidden';\n";
				$extra_html .= "        input.name = 'g-recaptcha-response';\n";
				$extra_html .= "        input.id = 'g-recaptcha-response';\n";
				$extra_html .= "        form.appendChild(input);\n";
				$extra_html .= "      }\n";
				$extra_html .= "      input.value = token;\n";
				$extra_html .= "      form.dataset.recaptchaProcessed = '1';\n";
				$extra_html .= "      HTMLFormElement.prototype.submit.call(form);\n";
				$extra_html .= "    });\n";
				$extra_html .= "  });\n";
				$extra_html .= "});\n";
				$extra_html .= "</script>\n";
			} else {
				$recaptcha = "<div class=\"{$captcha_name}\" data-sitekey=\"{$config['recaptcha_public_key']}\" data-theme=\"{$config['recaptcha_theme']}\" data-language=\"{$lang['language_code']}\"></div><script src=\"{$captcha_url}\" async defer></script>";
			}
		} else {
			$show_sec_code = true;
			$path = parse_url($config['http_home_url']);
			$img_src = ($path && isset($path['path'])) ? $path['path'] : '/';
			$sec_code = "<a class=\"gb-captcha\" onclick=\"GBReloadCaptcha(); return false;\" href=\"#\" title=\"{$lang['reload_code']}\"><span id=\"gb-captcha\"><img src=\"{$img_src}index.php?controller=antibot\" alt=\"{$lang['reload_code']}\" width=\"130\" height=\"46\" /></span></a>";
		}
	}

	return [
		'show_question' => $show_question,
		'question' => $question,
		'show_sec_code' => $show_sec_code,
		'sec_code' => $sec_code,
		'show_recaptcha' => $show_recaptcha,
		'recaptcha' => $recaptcha,
		'extra_html' => $extra_html,
	];
}

function dle_guestbook_check_antispam(): array {
	global $db, $config, $member_id, $user_group, $lang;

	$errors = [];

	$comments_question = !empty($user_group[$member_id['user_group']]['comments_question']);
	$captcha = !empty($user_group[$member_id['user_group']]['captcha']);

	$disable_comments_captcha = intval($user_group[$member_id['user_group']]['disable_comments_captcha'] ?? 0);
	if ($disable_comments_captcha && intval($member_id['comm_num'] ?? 0) >= $disable_comments_captcha) {
		$comments_question = false;
		$captcha = false;
	}

	if ($captcha) {
		if (!empty($config['allow_recaptcha'])) {
			if (!empty($_POST['g-recaptcha-response'])) {
				$reCaptcha = new ReCaptcha($config['recaptcha_private_key']);
				$resp = $reCaptcha->verifyResponse(get_ip(), $_POST['g-recaptcha-response']);
				if ($resp === null || !$resp->success) {
					$errors[] = $lang['recaptcha_fail'];
				}
			} else {
				$errors[] = $lang['recaptcha_fail'];
			}
		} elseif ((string)($_REQUEST['sec_code'] ?? '') != (string)($_SESSION['sec_code_session'] ?? '') || empty($_SESSION['sec_code_session'])) {
			$errors[] = $lang['recaptcha_fail'];
		}
	}

	if ($comments_question) {
		if (intval($_SESSION['question'] ?? 0)) {
			$answer = $db->super_query("SELECT id, answer FROM " . PREFIX . "_question WHERE id='" . intval($_SESSION['question']) . "'");
			$answers = explode("\n", $answer['answer'] ?? '');
			$pass_answer = false;
			$question_answer = trim(dle_strtolower((string)($_POST['question_answer'] ?? '')));

			if (count($answers) && $question_answer) {
				foreach ($answers as $a) {
					$a = trim(dle_strtolower($a));
					if ($a && $a == $question_answer) {
						$pass_answer = true;
						break;
					}
				}
			}

			if (!$pass_answer) {
				$errors[] = $lang['reg_err_24'];
			}
		} else {
			$errors[] = $lang['reg_err_24'];
		}
	}

	return $errors;
}

dle_guestbook_ensure_table();

$action = isset($_REQUEST['action']) ? (string)$_REQUEST['action'] : '';
$action = totranslit($action);

// Delete entry (admin)
if ($action === 'delete') {
	$id = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : 0;
	$user_hash = isset($_REQUEST['user_hash']) ? (string)$_REQUEST['user_hash'] : '';
	if ($id && $user_hash && $user_hash === $dle_login_hash && dle_guestbook_can_delete()) {
		$table = dle_guestbook_table();
		$db->query("DELETE FROM {$table} WHERE id='{$id}'");
		header("Location: " . $config['http_home_url'] . "index.php?do=guestbook");
		die();
	}
}

$alert_html = '';

// Add entry
if ($action === 'add' && isset($_POST['gb_submit'])) {
	$errors = [];

	$user_hash = isset($_POST['user_hash']) ? (string)$_POST['user_hash'] : '';
	if (!$user_hash || $user_hash !== $dle_login_hash) {
		$errors[] = $lang['sess_error'];
	}

	$_IP = get_ip();
	$_TIME = time();

	$name = isset($_POST['name']) ? trim((string)$_POST['name']) : '';
	$website = isset($_POST['website']) ? trim((string)$_POST['website']) : '';
	$message_raw = isset($_POST['message']) ? (string)$_POST['message'] : '';

	if ($is_logged) {
		$name = (string)($member_id['name'] ?? '');
		$website = '';
	}

	$name = htmlspecialchars(strip_tags($name), ENT_QUOTES, 'UTF-8');
	if (!$name) {
		$errors[] = $lang['news_err_1'];
	} elseif (dle_strlen($name) > 40) {
		$errors[] = $lang['news_err_1'];
	}

	$website = strip_tags($website);
	$website = preg_replace('#\s+#u', '', $website);
	if ($website && dle_strlen($website) > 255) {
		$website = dle_substr($website, 0, 255);
	}
	if ($website && !preg_match('#^(https?://)?[\pL0-9\-._~%]+(?:\:[0-9]{1,5})?(?:/[^\s<>]*)?$#iu', $website)) {
		$errors[] = $lang['feed_err_3'] ?? 'Invalid website address';
	}

	$parse = new ParseFilter();
	$parse->safe_mode = true;
	$parse->remove_html = false;
	$parse->allow_url = true;
	$parse->allow_image = false;
	$parse->allow_video = false;
	$parse->allow_media = false;
	$parse->allowbbcodes = false;

	$message = $parse->BB_Parse($parse->process(trim($message_raw)), false);
	if (!trim(strip_tags($message))) {
		$errors[] = $lang['news_err_40'] ?? 'Empty message';
	}
	// Guestbook: allow very short messages (min 2 chars) independent of global comments settings.
	$guestbook_minlen = 2;
	if (dle_strlen(str_replace(' ', '', strip_tags(trim($message)))) < $guestbook_minlen) {
		$errors[] = $lang['news_err_40'];
	}

	if (!empty($user_group[$member_id['user_group']]['spamfilter'])) {
		$mail = $is_logged ? (string)($member_id['email'] ?? '') : '';
		$row = $db->super_query("SELECT * FROM " . PREFIX . "_spam_log WHERE ip = '{$_IP}'");
		if (!isset($row['id']) || !isset($row['email']) || !$row['id'] || !$row['email']) {
			$sfs = new StopSpam($config['spam_api_key'], $user_group[$member_id['user_group']]['spamfilter']);
			$args = ['ip' => $_IP, 'email' => $mail];
			if ($sfs->is_spammer($args)) {
				if (empty($row['id'])) {
					$db->query("INSERT INTO " . PREFIX . "_spam_log (ip, is_spammer, email, date) VALUES ('{$_IP}','1', '" . $db->safesql($mail) . "', '{$_TIME}')");
				} else {
					$db->query("UPDATE " . PREFIX . "_spam_log SET is_spammer='1', email='" . $db->safesql($mail) . "' WHERE id='" . intval($row['id']) . "'");
				}
				$errors[] = $lang['reg_err_29'] . ' ';
			} else {
				if (empty($row['id'])) {
					$db->query("INSERT INTO " . PREFIX . "_spam_log (ip, is_spammer, email, date) VALUES ('{$_IP}','0', '" . $db->safesql($mail) . "', '{$_TIME}')");
				} else {
					$db->query("UPDATE " . PREFIX . "_spam_log SET email='" . $db->safesql($mail) . "' WHERE id='" . intval($row['id']) . "'");
				}
			}
		} else {
			if (!empty($row['is_spammer'])) {
				$errors[] = $lang['reg_err_29'] . ' ';
			}
		}
	}

	$errors = array_merge($errors, dle_guestbook_check_antispam());

	if (!count($errors)) {
		$table = dle_guestbook_table();
		$db->query(
			"INSERT INTO {$table} (user_id, name, website, message, ip, date, is_register, user_group) VALUES ("
			. "'" . intval($is_logged ? ($member_id['user_id'] ?? 0) : 0) . "',"
			. "'" . $db->safesql($name) . "',"
			. "'" . $db->safesql($website) . "',"
			. "'" . $db->safesql($message) . "',"
			. "'" . $db->safesql($_IP) . "',"
			. "'" . intval($_TIME) . "',"
			. "'" . intval($is_logged ? 1 : 0) . "',"
			. "'" . intval($member_id['user_group'] ?? 5) . "'"
			. ")"
		);

		header("Location: " . $config['http_home_url'] . "index.php?do=guestbook");
		die();
	}

	$alert_html = '<div class="gb-alert gb-alert--error">' . implode('<br>', $errors) . '</div>';
}


$per_page = max(1, intval($config['comm_nummers'] ?? 30));

$table = dle_guestbook_table();
$row_count = $db->super_query("SELECT COUNT(*) as count FROM {$table}");
$total = isset($row_count['count']) ? intval($row_count['count']) : 0;

$pages_count = $per_page ? (int)ceil($total / $per_page) : 1;
if ($pages_count < 1) $pages_count = 1;

// For chat-like UX: default to the last page so newest messages are visible.
if (isset($_GET['cstart'])) {
	$page = intval($_GET['cstart']);
} else {
	$page = $pages_count;
}
if ($page < 1) $page = 1;
if ($page > $pages_count) $page = $pages_count;

$offset = ($page - 1) * $per_page;


$rows = $db->super_query(
	"SELECT g.id, g.user_id, g.name, g.website, g.message, g.date, g.is_register, g.user_group, u.foto AS user_foto, u.email AS user_email "
		. "FROM {$table} g "
		. "LEFT JOIN " . USERPREFIX . "_users u ON (u.user_id=g.user_id) "
		. "ORDER BY g.id ASC LIMIT {$offset}, {$per_page}",
	true
);

$can_delete = dle_guestbook_can_delete();

$entries_html = '';
if (is_array($rows) && count($rows)) {
	foreach ($rows as $row) {
		$id = intval($row['id']);
		$name = htmlspecialchars(stripslashes((string)$row['name']), ENT_QUOTES, 'UTF-8');
		$website = stripslashes((string)($row['website'] ?? ''));
		$website = htmlspecialchars($website, ENT_QUOTES, 'UTF-8');
		$message = stripslashes((string)$row['message']);
		$date = isset($row['date']) ? intval($row['date']) : 0;
		$user_group_id = intval($row['user_group'] ?? 5);
		$is_admin_author = ($user_group_id === 1);
		$is_me = false;
		if ($is_logged && !empty($row['is_register']) && !empty($row['user_id']) && isset($member_id['user_id'])) {
			$is_me = (intval($row['user_id']) === intval($member_id['user_id']));
		}
		$me_badge = ($is_me && $is_logged) ? '<span class="gb-badge gb-badge--me">tu</span>' : '';

		$avatar_url = '';
		if (!empty($row['is_register']) && !empty($row['user_id'])) {
			$user_foto = !empty($row['user_foto']) ? trim((string)$row['user_foto']) : '';
			$user_email = !empty($row['user_email']) ? trim((string)$row['user_email']) : '';

			if ($user_foto) {
				if (filter_var($user_foto, FILTER_VALIDATE_EMAIL)) {
					$avatar_url = 'https://www.gravatar.com/avatar/' . md5(trim(strtolower($user_foto))) . '?s=80';
				} elseif (strpos($user_foto, "//") === 0) {
					$avatar_url = 'http:' . $user_foto;
				} else {
					$parsed = @parse_url($user_foto);
					if (isset($parsed['host']) && $parsed['host']) {
						$avatar_url = $user_foto;
					} else {
						$avatar_url = $config['http_home_url'] . 'uploads/fotos/' . $user_foto;
					}
				}
			} elseif ($user_email && filter_var($user_email, FILTER_VALIDATE_EMAIL)) {
				$avatar_url = 'https://www.gravatar.com/avatar/' . md5(trim(strtolower($user_email))) . '?s=80&d=mp';
			}
		}

		$avatar_letter = $name ? dle_substr($name, 0, 1) : 'G';
		$avatar_letter_upper = function_exists('mb_strtoupper')
			? mb_strtoupper($avatar_letter, 'UTF-8')
			: strtoupper($avatar_letter);
		$avatar_letter = htmlspecialchars($avatar_letter_upper, ENT_QUOTES, 'UTF-8');
		$avatar_inner = $avatar_letter;
		if ($avatar_url) {
			$avatar_inner = '<img class="gb-avatar__img" src="' . htmlspecialchars($avatar_url, ENT_QUOTES, 'UTF-8') . '" alt="" loading="lazy">';
		}

		$site_html = '';
		if ($website) {
			$link = $website;
			if (!preg_match('#^https?://#i', $link)) {
				$link = 'https://' . $link;
			}
			$site_html = '<a class="gb-site" href="' . $link . '" rel="nofollow noopener" target="_blank">' . $website . '</a>';
		}

		$delete_html = '';
		if ($can_delete) {
			$del_url = $config['http_home_url'] . 'index.php?do=guestbook&action=delete&id=' . $id . '&user_hash=' . urlencode($dle_login_hash);
			$delete_html = '<a class="gb-del" href="' . $del_url . '" onclick="return confirm(\'Ștergi acest mesaj?\');" title="' . htmlspecialchars(($lang['comm_delete'] ?? 'Delete'), ENT_QUOTES, 'UTF-8') . '">×</a>';
		}

		$entries_html .= '<div class="gb-msg' . ($is_me ? ' gb-msg--me' : '') . ($is_admin_author ? ' gb-msg--admin' : '') . '" id="gb-' . $id . '">';
		$entries_html .= '<div class="gb-avatar' . ($is_admin_author ? ' gb-avatar--admin' : '') . '">' . $avatar_inner . '</div>';
		$entries_html .= '<div class="gb-bubble">';
		$entries_html .= '<div class="gb-bubble__head">';
		$entries_html .= '<span class="gb-name">' . $name . '</span>';
		if ($me_badge) {
			$entries_html .= $me_badge;
		}
		if ($is_admin_author) {
			$entries_html .= '<span class="gb-badge gb-badge--admin">admin</span>';
		}
		if ($site_html) {
			$entries_html .= $site_html;
		}
		$entries_html .= $delete_html;
		$entries_html .= '</div>';
		$entries_html .= '<div class="gb-bubble__body">' . $message . '</div>';
		$entries_html .= '<div class="gb-meta"><span class="gb-time">' . langdate('j F Y, H:i', $date) . '</span></div>';
		$entries_html .= '</div>';
		$entries_html .= '</div>';
	}
} else {
	$entries_html = '<div class="gb-empty">Fii primul care lasă un mesaj.</div>';
}

$pagination_html = '';
if ($pages_count > 1) {
	$pagination_html .= '<div class="gb-nav">';
	for ($p = 1; $p <= $pages_count; $p++) {
		if ($p == $page) {
			$pagination_html .= '<span class="gb-nav__item is-active">' . $p . '</span>';
		} else {
			$url = $config['http_home_url'] . 'index.php?do=guestbook&cstart=' . $p;
			$pagination_html .= '<a class="gb-nav__item" href="' . $url . '">' . $p . '</a>';
		}
	}
	$pagination_html .= '</div>';
}

$antispam = dle_guestbook_build_antispam_blocks();

$form_html = '';
$form_html .= '<form id="guestbook-form" class="gb-form" method="post" action="' . $config['http_home_url'] . 'index.php?do=guestbook">';
$form_html .= '<input type="hidden" name="action" value="add">';
$form_html .= '<input type="hidden" name="user_hash" value="' . htmlspecialchars($dle_login_hash, ENT_QUOTES, 'UTF-8') . '">';

if (!$is_logged) {
	$form_html .= '<div class="gb-form__row">';
	$form_html .= '<label class="gb-label">Nume</label>';
		$form_html .= '<input class="gb-input gb-input--field" type="text" name="name" maxlength="40" required>';
	$form_html .= '</div>';
	$form_html .= '<div class="gb-form__row">';
	$form_html .= '<label class="gb-label">Website (opțional)</label>';
		$form_html .= '<input class="gb-input gb-input--field" type="text" name="website" maxlength="255" placeholder="https://exemplu.ro">';
	$form_html .= '</div>';
} else {
	$form_html .= '<div class="gb-form__row gb-form__row--as">Scrii ca <b>' . htmlspecialchars($member_id['name'], ENT_QUOTES, 'UTF-8') . '</b></div>';
}

$form_html .= '<div class="gb-composer">';
	$form_html .= '<div class="gb-inputwrap">';
		$form_html .= '<textarea class="gb-input gb-input--msg" name="message" rows="1" placeholder="Scrie un mesaj…" required></textarea>';
		$form_html .= '<button class="gb-iconbtn gb-iconbtn--inside" type="button" onclick="GBToggleEmoji()" aria-label="Emoji" title="Emoji">😊</button>';
	$form_html .= '</div>';
	$form_html .= '<button class="gb-send" type="submit" name="gb_submit" aria-label="Trimite" title="Trimite"><span class="gb-send__icon">➤</span></button>';
$form_html .= '</div>';

$form_html .= '<div id="gb-emoji-panel" class="gb-emoji-panel" hidden>';
$emoji_list = ['😀','😁','😂','🤣','😊','😍','😘','😎','😢','😭','😡','🤯','👍','👎','🙏','🔥','💯','🎉','✨','❤️','🤍','🤝','✅','❌','⭐'];
foreach ($emoji_list as $emj) {
	$form_html .= '<button class="gb-emoji__btn" type="button" onclick="GBInsertEmoji(\'' . $emj . '\')">' . $emj . '</button>';
}
$form_html .= '</div>';

if (!empty($antispam['show_question'])) {
	$form_html .= '<div class="gb-form__row">';
	$form_html .= '<label class="gb-label">' . ($lang['question'] ?? 'Question') . '</label>';
	$form_html .= '<div class="gb-question">' . $antispam['question'] . '</div>';
		$form_html .= '<input class="gb-input gb-input--field" type="text" name="question_answer" autocomplete="off" required>';
	$form_html .= '</div>';
}

if (!empty($antispam['show_recaptcha'])) {
	$form_html .= '<div class="gb-form__row">';
	$form_html .= '<label class="gb-label">Verificare anti-spam</label>';
	$form_html .= '<div class="gb-hint">Completează verificarea de mai jos ca să poți trimite mesajul.</div>';
	$form_html .= $antispam['recaptcha'];
	$form_html .= '</div>';
}
if (!empty($antispam['show_sec_code'])) {
	$form_html .= '<div class="gb-form__row">';
	$form_html .= '<label class="gb-label" for="gb-sec-code">Cod din imagine</label>';
	$form_html .= '<div class="gb-hint">Introdu codul din imagine. Click pe imagine pentru reîmprospătare.</div>';
	$form_html .= '<div class="gb-form__row gb-form__row--captcha">';
	$form_html .= '<div>' . $antispam['sec_code'] . '</div>';
		$form_html .= '<input id="gb-sec-code" class="gb-input gb-input--field" type="text" name="sec_code" autocomplete="off" required>';
	$form_html .= '</div>';
	$form_html .= '</div>';
}

$form_html .= '</form>';

$form_html .= <<<HTML
<script>
function GBAutoGrow(ta) {
	if (!ta) return;
	ta.style.height = 'auto';
	var min = 50;
	var max = 140;
	var h = ta.scrollHeight || min;
	// Most themes report ~58-60px scrollHeight for a single line.
	// Force a compact one-line height (50px) and grow only when needed.
	if (h <= 60) h = min;
	h = Math.max(min, Math.min(h, max));
	ta.style.height = h + 'px';
}

function GBToggleEmoji() {
	var panel = document.getElementById('gb-emoji-panel');
	if (!panel) return;
	panel.hidden = !panel.hidden;
}

function GBInsertEmoji(ch) {
  var ta = document.querySelector('#guestbook-form textarea[name="message"]');
  if (!ta) return;
  var start = ta.selectionStart || 0;
  var end = ta.selectionEnd || 0;
  var value = ta.value || '';
  ta.value = value.slice(0, start) + ch + value.slice(end);
  var pos = start + ch.length;
  ta.focus();
  ta.setSelectionRange(pos, pos);
	GBAutoGrow(ta);
	var panel = document.getElementById('gb-emoji-panel');
	if (panel) panel.hidden = true;
}

function GBReloadCaptcha() {
  var cap = document.getElementById('gb-captcha');
  if (!cap) return;
  var timeval = new Date().getTime();
	cap.innerHTML = '<img src="' + dle_root + 'index.php?controller=antibot&rand=' + timeval + '" width="130" height="46" alt="">';
}

function GBInit() {
	var form = document.getElementById('guestbook-form');
	if (!form) return;

	if (form.dataset.gbBound === '1') {
		// Still do cheap one-off UI sync on re-init
		var thread = document.querySelector('.gb-thread');
		if (thread) thread.scrollTop = thread.scrollHeight;
		var panel = document.getElementById('gb-emoji-panel');
		if (panel) panel.hidden = true;
		return;
	}
	form.dataset.gbBound = '1';

	var ta = form.querySelector('textarea[name="message"]');
	if (ta) {
		GBAutoGrow(ta);
		ta.addEventListener('input', function () { GBAutoGrow(ta); });
		ta.addEventListener('keydown', function (e) {
			if (e.key === 'Enter' && !e.shiftKey) {
				e.preventDefault();
				form.requestSubmit();
			}
		});
	}

	document.addEventListener('click', function (e) {
		var panel = document.getElementById('gb-emoji-panel');
		if (!panel || panel.hidden) return;
		if (panel.contains(e.target)) return;
		var btn = document.querySelector('.gb-iconbtn');
		if (btn && btn.contains(e.target)) return;
		panel.hidden = true;
	});

	var thread = document.querySelector('.gb-thread');
	if (thread) thread.scrollTop = thread.scrollHeight;
	var panel = document.getElementById('gb-emoji-panel');
	if (panel) panel.hidden = true;
}

try { GBInit(); } catch (e) {}
</script>
HTML;

$form_html .= $antispam['extra_html'] ?? '';

if ($tpl->load_template('guestbook.tpl')) {
	$tpl->set('{guestbook-alert}', $alert_html);
	$tpl->set('{guestbook-form}', $form_html);
	$tpl->set('{guestbook-entries}', $entries_html);
	$tpl->set('{guestbook-navigation}', $pagination_html);
	$tpl->compile('content');
	$tpl->clear();
} else {
	$tpl->result['content'] .= $alert_html . $form_html . $entries_html . $pagination_html;
}

?>
