<?php
/**
 * Czech QR payment (Short Payment Descriptor) support.
 *
 * @package Vachr Short-Term Rental Reservations
 * @license GPLv2 or later
 */

if (!defined('ABSPATH')) exit;

class VSTRB_Payment_QR {
	public static function supplier_account_details() {
		$raw = trim((string) get_option('vstrb_invoice_supplier_bank_account', ''));
		$iban = strtoupper((string) preg_replace('/[^A-Z0-9]/i', '', $raw));
		$country = preg_match('/^[A-Z]{2}/', $iban) ? substr($iban, 0, 2) : '';
		$account_number = $raw;

		if ($country !== '' && strlen($iban) > 4) {
			$account_number = substr($iban, 4);
		}

		if (preg_match('/^CZ[0-9]{22}$/', $iban)) {
			$bank_code = substr($iban, 4, 4);
			$prefix = ltrim(substr($iban, 8, 6), '0');
			$number = ltrim(substr($iban, 14, 10), '0');
			$number = $number !== '' ? $number : '0';
			$account_number = ($prefix !== '' ? $prefix . '-' : '') . $number . '/' . $bank_code;
		}

		return [
			'iban' => $country !== '' ? $iban : '',
			'account_number' => $account_number,
			'country' => $country,
		];
	}

	public static function payload($amount, $currency, $reference = '', $message = '') {
		$iban = self::supplier_czech_iban();
		$currency = strtoupper(trim((string) $currency));
		$amount = round((float) $amount, 2);
		if ($iban === '' || $currency !== 'CZK' || $amount <= 0) {
			return '';
		}

		$parts = [
			'SPD*1.0',
			'ACC:' . $iban,
			'AM:' . number_format($amount, 2, '.', ''),
			'CC:CZK',
		];

		$variable_symbol = preg_replace('/\D+/', '', (string) $reference);
		if ($variable_symbol !== '') {
			$parts[] = 'X-VS:' . substr($variable_symbol, -10);
		}

		$message = self::sanitize_message($message !== '' ? $message : $reference);
		if ($message !== '') {
			$parts[] = 'MSG:' . $message;
		}

		return implode('*', $parts);
	}

	public static function render($payload, $label = '') {
		$payload = trim((string) $payload);
		if ($payload === '') {
			return;
		}
		if ($label === '') {
			$label = sprintf('%s (QR)', __('Bank transfer', 'vachr-short-term-rental-reservations'));
		}
		?>
		<div class="vstrb-payment-qr" data-vstrb-payment-qr="<?php echo esc_attr($payload); ?>" style="margin-top:16px">
			<strong><?php echo esc_html($label); ?></strong>
			<div class="vstrb-payment-qr-code" style="margin-top:8px"></div>
		</div>
		<?php
	}

	public static function render_assets() {
		if (!wp_script_is('vstrb-qrcode', 'registered')) {
			wp_register_script('vstrb-qrcode', VSTRB_PLUGIN_URL . 'assets/vendor/qrcodejs/qrcode.min.js', [], '1.0.0', true);
		}
		if (!wp_script_is('vstrb-payment-qr', 'registered')) {
			wp_register_script('vstrb-payment-qr', VSTRB_PLUGIN_URL . 'assets/payment-qr.js', ['vstrb-qrcode'], VSTRB_VERSION, true);
		}

		wp_enqueue_script('vstrb-qrcode');
		wp_enqueue_script('vstrb-payment-qr');
		wp_print_footer_scripts();
	}

	private static function supplier_czech_iban() {
		$account = self::supplier_account_details();
		return ($account['country'] ?? '') === 'CZ' ? (string) ($account['iban'] ?? '') : '';
	}

	private static function sanitize_message($message) {
		$message = wp_strip_all_tags((string) $message);
		$message = preg_replace('/[\x00-\x1F\x7F:*]/u', ' ', $message);
		$message = preg_replace('/\s+/u', ' ', trim((string) $message));
		if (function_exists('mb_substr')) {
			return mb_substr((string) $message, 0, 60);
		}
		return substr((string) $message, 0, 60);
	}
}
