<?php

/**
 * WebEngine CMS
 * https://webenginecms.org/
 *
 * @version 1.2.6
 * @author Gabo Development <https://gabodevelop.com/>
 * @copyright (c) 2026 Gabriel Development, All Rights Reserved
 */

if (!isLoggedIn()) redirect(1, 'login');

$pageTitle = lang('module_titles_txt_28', true) ?: 'Buy Zen';

try {
	if (!mconfig('active')) throw new Exception(lang('error_47', true));
	$db = Connection::Database('MuOnline');
	$common = new common();
	$Character = new Character();
	$AccountCharacters = $Character->AccountCharacter($_SESSION['username']);
	if (!is_array($AccountCharacters)) throw new Exception(lang('error_46', true));
	$maxZen = mconfig('max_zen');
	$exchangeRatio = mconfig('exchange_ratio');
	$incrementRate = mconfig('increment_rate');
	$buyOptions = array();
	for ($multiplier = 1; $multiplier <= floor($maxZen / $incrementRate); $multiplier++) {
		$zenAmount = $multiplier * $incrementRate;
		$creditAmount = ceil($zenAmount / $exchangeRatio);
		$buyOptions[] = $creditAmount;
	}
	if (isset($_POST['submit']) && isset($_POST['character']) && isset($_POST['credits'])) {
		try {
			if ($common->accountOnline($_SESSION['username'])) throw new Exception(lang('error_28', true));
			if (!in_array($_POST['credits'], $buyOptions)) throw new Exception(lang('error_24', true));
			$char = $_POST['character'];
			$zen = $_POST['credits'] * $exchangeRatio;
			if (!Validator::UnsignedNumber($_POST['credits'])) throw new Exception(lang('error_25', true));
			if ($zen > $maxZen) throw new Exception(lang('error_25', true));
			if (!in_array($char, $AccountCharacters)) throw new Exception(lang('error_24', true));
			$characterData = $Character->CharacterData($char);
			if (!is_array($characterData)) throw new Exception(lang('error_25', true));
			$charZen = $characterData[_CLMN_CHR_ZEN_];
			if ($charZen + $zen > $maxZen) throw new Exception(lang('error_55', true));
			$creditSystem = new CreditSystem();
			$creditSystem->setConfigId(mconfig('credit_config'));
			$configSettings = $creditSystem->showConfigs(true);
			switch ($configSettings['config_user_col_id']) {
				case 'userid':
					$creditSystem->setIdentifier($_SESSION['userid']);
					break;
				case 'username':
					$creditSystem->setIdentifier($_SESSION['username']);
					break;
				case 'character':
					$creditSystem->setIdentifier($char);
					break;
				default:
					throw new Exception("Invalid identifier (credit system).");
			}
			$creditSystem->subtractCredits($_POST['credits']);
			if (!$db->query("UPDATE " . _TBL_CHR_ . " SET " . _CLMN_CHR_ZEN_ . " = " . _CLMN_CHR_ZEN_ . " + ? WHERE " . _CLMN_CHR_NAME_ . " = ?", array($zen, $characterData[_CLMN_CHR_NAME_])));
			message('success', lang('success_21', true));
			message('info', number_format($zen) . lang('buyzen_txt_2', true) . $char);
		} catch (Exception $ex) {
			message('error', $ex->getMessage());
		}
	}
	$exchangeLabel = (function_exists('lang') && lang('buyzen_txt_6', true)) ? lang('buyzen_txt_6', true) : 'credit(s)';
	echo '<div class="nexora-usercp-page nexora-buyzen-page">';
	echo '<header class="nexora-usercp-page-header"><h1 class="nexora-usercp-page-title">' . htmlspecialchars($pageTitle) . '</h1>';
	echo '<p class="nexora-usercp-page-subtitle">' . number_format($exchangeRatio) . ' Zen = 1 ' . $exchangeLabel . '</p></header>';
	echo '<div class="nexora-usercp-panel nexora-buyzen-panel">';
	echo '<form action="" method="post" class="nexora-buyzen-form">';
	echo '<div class="nexora-usercp-panel-body">';
	echo '<div class="nexora-buyzen-intro">' . lang('buyzen_txt_3', true) . ' &amp; ' . lang('buyzen_txt_4', true) . '</div>';
	echo '<div class="nexora-buyzen-row">';
	echo '<div class="nexora-buyzen-field"><label class="nexora-usercp-label" for="buyzen-character">' . lang('buyzen_txt_3', true) . '</label><select id="buyzen-character" name="character" class="nexora-usercp-select nexora-buyzen-select" required>';
	foreach ($AccountCharacters as $char) echo '<option value="' . htmlspecialchars($char) . '">' . htmlspecialchars($char) . '</option>';
	echo '</select></div>';
	echo '<div class="nexora-buyzen-field nexora-buyzen-amount"><label class="nexora-usercp-label" for="buyzen-credits">' . lang('buyzen_txt_4', true) . '</label><select id="buyzen-credits" name="credits" class="nexora-usercp-select nexora-buyzen-select" required>';
	foreach ($buyOptions as $creditValue) {
		$zenValue = $creditValue * $exchangeRatio;
		if ($zenValue > $maxZen) continue;
		echo '<option value="' . $creditValue . '">' . number_format($zenValue) . ' Zen — ' . $creditValue . ' ' . lang('buyzen_txt_6', true) . '</option>';
	}
	echo '</select></div>';
	echo '<div class="nexora-buyzen-submit"><label class="nexora-usercp-label nexora-buyzen-label-hidden">&nbsp;</label><button type="submit" name="submit" value="submit" class="nexora-usercp-btn nexora-buyzen-btn">' . lang('buyzen_txt_5', true) . '</button></div>';
	echo '</div></div></form></div></div>';
} catch (Exception $ex) {
	message('error', $ex->getMessage());
}
