<?php
/**
 * WebEngine CMS - Twitch Streamer Widget
 * Configuración del botón lateral y previsualización Twitch (template nexoraves6).
 *
 * @version 1.0
 * @author Gabo Dev <https://www.gabodevelop.com/>
 */

if (!defined('access')) die('Direct access not permitted.');

$moduleName = 'twitch_streamer';
$xmlPath = __PATH_MODULE_CONFIGS__ . $moduleName . '.xml';

function saveTwitchStreamerChanges($xmlPath) {
	if (!is_string($xmlPath) || $xmlPath === '' || !is_writable($xmlPath)) {
		message('error', 'The configuration file is not writable.');
		return;
	}
	$xml = simplexml_load_file($xmlPath);
	if (!$xml) {
		message('error', 'Error loading config file.');
		return;
	}
	$xml->active = isset($_POST['setting_1']) && $_POST['setting_1'] == '1' ? '1' : '0';
	$xml->channel = isset($_POST['setting_2']) ? trim($_POST['setting_2']) : '';
	$xml->button_label = isset($_POST['setting_3']) ? trim($_POST['setting_3']) : 'Twitch';
	$save = $xml->asXML($xmlPath);
	if ($save) {
		message('success', 'Twitch Streamer settings saved.');
	} else {
		message('error', 'Error saving changes.');
	}
}

if (isset($_POST['submit_changes'])) {
	saveTwitchStreamerChanges($xmlPath);
}

loadModuleConfigs($moduleName);
$twitch_active = mconfig('active');
$twitch_active = is_array($twitch_active) ? 0 : (int)$twitch_active;
$twitch_channel = mconfig('channel');
$twitch_channel = is_array($twitch_channel) ? '' : (string)$twitch_channel;
$twitch_label = mconfig('button_label');
$twitch_label = is_array($twitch_label) ? 'Twitch' : (string)$twitch_label;
?>
<h2>Twitch Streamer Settings</h2>
<p>Show a lateral button above the footer (nexoraves6). When clicked, a panel slides to the left with the Twitch live preview.</p>
<form action="" method="post">
	<table class="table table-striped table-bordered table-hover module_config_tables">
		<tr>
			<th>Status</th>
			<td><?php enabledisableCheckboxes('setting_1', $twitch_active, 'Enabled', 'Disabled'); ?></td>
		</tr>
		<tr>
			<th>Twitch channel (username)</th>
			<td>
				<input type="text" name="setting_2" class="form-control" value="<?php echo htmlspecialchars($twitch_channel); ?>" placeholder="e.g. ninja" />
				<span class="help-block">The Twitch username of the streamer (no URL).</span>
			</td>
		</tr>
		<tr>
			<th>Button label</th>
			<td>
				<input type="text" name="setting_3" class="form-control" value="<?php echo htmlspecialchars($twitch_label); ?>" placeholder="Twitch" />
			</td>
		</tr>
		<tr>
			<td colspan="2">
				<button type="submit" name="submit_changes" class="btn btn-primary">Save changes</button>
			</td>
		</tr>
	</table>
</form>
