<?php
/**
 * CloudScale shared Telegram notification helper.
 *
 * Credentials are stored under shared wp_options keys so any CloudScale plugin
 * that includes this file can send and configure Telegram without duplicating logic.
 *
 * DO NOT EDIT THIS FILE in individual plugin directories.
 * Edit shared-admin-ui/class-cloudscale-telegram.php and run sync-admin-css.sh.
 */

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

if ( class_exists( 'CloudScale_Telegram' ) ) {
	return;
}

class CloudScale_Telegram {

	const OPTION_TOKEN   = 'cloudscale_telegram_bot_token';
	const OPTION_CHAT_ID = 'cloudscale_telegram_chat_id';

	public static function is_configured(): bool {
		return ! empty( get_option( self::OPTION_TOKEN ) ) && ! empty( get_option( self::OPTION_CHAT_ID ) );
	}

	/**
	 * Build the alert prefix line: "{emoji} Domain : Source\nLEVEL\n\n"
	 *
	 * @param string $source  Human-readable plugin/feature name, e.g. "Backup and Restore".
	 * @param string $level   One of: info, warning, error, critical.
	 */
	private static function alert_prefix( string $source, string $level ): string {
		$host   = (string) ( parse_url( home_url(), PHP_URL_HOST ) ?: '' );
		$domain = implode( '.', array_map( 'ucfirst', explode( '.', strtolower( $host ) ) ) );

		$emojis = [
			'info'     => "\u{2705}",
			'warning'  => "\u{26A0}\u{FE0F}",
			'error'    => "\u{274C}",
			'critical' => "\u{1F6A8}",
		];
		$emoji = $emojis[ $level ] ?? $emojis['info'];
		$label = strtoupper( $level ?: 'INFO' );

		$header = $source ? $domain . ' : ' . $source : $domain;
		return $emoji . ' ' . $header . "\n" . $label . "\n\n";
	}

	/**
	 * Send a Telegram message. Returns true on success.
	 *
	 * @param string $text    Message body.
	 * @param string $source  Plugin/feature name shown in the header (e.g. "Backup and Restore").
	 * @param string $level   Alert level: info, warning, error, critical.
	 */
	public static function send( string $text, string $source = '', string $level = 'info' ): bool {
		$token   = trim( (string) get_option( self::OPTION_TOKEN, '' ) );
		$chat_id = trim( (string) get_option( self::OPTION_CHAT_ID, '' ) );
		if ( ! $token || ! $chat_id ) {
			return false;
		}

		$full = self::alert_prefix( $source, $level ) . $text;

		$response = wp_remote_post(
			'https://api.telegram.org/bot' . rawurlencode( $token ) . '/sendMessage',
			[
				'timeout' => 10,
				'headers' => [ 'Content-Type' => 'application/json' ],
				'body'    => wp_json_encode( [ 'chat_id' => $chat_id, 'text' => $full ] ),
			]
		);

		if ( is_wp_error( $response ) ) {
			return false;
		}

		return (int) wp_remote_retrieve_response_code( $response ) === 200;
	}

	/**
	 * Save shared Telegram credentials from POST data.
	 * Call from a plugin's save AJAX handler after nonce verification.
	 */
	public static function save_from_post(): void {
		// phpcs:disable WordPress.Security.NonceVerification.Missing -- caller is responsible for nonce check
		update_option( self::OPTION_TOKEN,   sanitize_text_field( wp_unslash( $_POST['telegram_token']   ?? '' ) ) );
		update_option( self::OPTION_CHAT_ID, sanitize_text_field( wp_unslash( $_POST['telegram_chat_id'] ?? '' ) ) );
		// phpcs:enable WordPress.Security.NonceVerification.Missing
	}

	/**
	 * Register the shared AJAX handlers (test + fetch-chat-id).
	 * Safe to call from multiple plugins; handlers are registered only once.
	 */
	public static function register_ajax(): void {
		if ( ! has_action( 'wp_ajax_cloudscale_telegram_fetch_chat_id' ) ) {
			add_action( 'wp_ajax_cloudscale_telegram_fetch_chat_id', static function (): void {
				if ( ! current_user_can( 'manage_options' ) ) {
					wp_send_json_error( 'Forbidden', 403 );
				}
				check_ajax_referer( 'cloudscale_telegram_fetch', 'nonce' );

				$token = sanitize_text_field( wp_unslash( $_POST['telegram_token'] ?? '' ) );
				if ( ! $token ) {
					wp_send_json_error( 'Bot token is required.' );
					return;
				}

				$response = wp_remote_get(
					'https://api.telegram.org/bot' . rawurlencode( $token ) . '/getUpdates',
					[ 'timeout' => 10 ]
				);

				if ( is_wp_error( $response ) ) {
					wp_send_json_error( 'Request failed: ' . $response->get_error_message() );
					return;
				}

				$code = (int) wp_remote_retrieve_response_code( $response );
				$body = wp_remote_retrieve_body( $response );
				$data = json_decode( $body, true );

				if ( $code !== 200 || empty( $data['ok'] ) ) {
					$detail = is_array( $data ) ? ( $data['description'] ?? $body ) : $body;
					wp_send_json_error( "Telegram HTTP {$code}: {$detail}" );
					return;
				}

				if ( empty( $data['result'] ) ) {
					wp_send_json_error( 'No messages yet. Send any message to your bot on Telegram first, then try again.' );
					return;
				}

				$chat_id = null;
				foreach ( $data['result'] as $update ) {
					$chat_id = $update['message']['chat']['id']
						?? $update['channel_post']['chat']['id']
						?? $update['my_chat_member']['chat']['id']
						?? null;
					if ( $chat_id !== null ) {
						break;
					}
				}

				if ( $chat_id === null ) {
					wp_send_json_error( 'Could not find a chat ID in the updates.' );
					return;
				}

				wp_send_json_success( [ 'chat_id' => (string) $chat_id ] );
			} );
		}

		if ( has_action( 'wp_ajax_cloudscale_telegram_test' ) ) {
			return;
		}
		add_action( 'wp_ajax_cloudscale_telegram_test', static function (): void {
			if ( ! current_user_can( 'manage_options' ) ) {
				wp_send_json_error( 'Forbidden', 403 );
			}
			check_ajax_referer( 'cloudscale_telegram_test', 'nonce' );

			// phpcs:disable WordPress.Security.NonceVerification.Missing -- nonce verified above
			$token   = sanitize_text_field( wp_unslash( $_POST['telegram_token']   ?? '' ) );
			$chat_id = sanitize_text_field( wp_unslash( $_POST['telegram_chat_id'] ?? '' ) );
			$source  = sanitize_text_field( wp_unslash( $_POST['test_source'] ?? '' ) ) ?: 'Telegram';
			// phpcs:enable WordPress.Security.NonceVerification.Missing

			// Fall back to stored credentials (used by the credentials panel test button).
			if ( ! $token )   { $token   = (string) get_option( self::OPTION_TOKEN,   '' ); }
			if ( ! $chat_id ) { $chat_id = (string) get_option( self::OPTION_CHAT_ID, '' ); }

			if ( ! $token || ! $chat_id ) {
				wp_send_json_error( 'Bot token and chat ID are required.' );
				return;
			}

			$prefix   = self::alert_prefix( $source, 'info' );
			$response = wp_remote_post(
				'https://api.telegram.org/bot' . rawurlencode( $token ) . '/sendMessage',
				[
					'timeout' => 10,
					'headers' => [ 'Content-Type' => 'application/json' ],
					'body'    => wp_json_encode( [ 'chat_id' => $chat_id, 'text' => $prefix . 'Test message sent successfully. Alerts are working.' ] ),
				]
			);

			if ( is_wp_error( $response ) ) {
				wp_send_json_error( 'Telegram request failed: ' . $response->get_error_message() );
				return;
			}

			$code = (int) wp_remote_retrieve_response_code( $response );
			if ( $code !== 200 ) {
				$body    = wp_remote_retrieve_body( $response );
				$decoded = json_decode( $body, true );
				$detail  = is_array( $decoded ) ? ( $decoded['description'] ?? $body ) : $body;
				wp_send_json_error( "Telegram HTTP {$code}: {$detail}" );
				return;
			}

			wp_send_json_success( [ 'msg' => 'Test message sent.' ] );
		} );
	}

	/**
	 * Render the Telegram settings card.
	 *
	 * @param string $text_domain  Plugin text domain for i18n.
	 */
	public static function render_settings_fields( string $text_domain, string $source = '' ): void {
		static $js_output = false;

		$token       = esc_attr( (string) get_option( self::OPTION_TOKEN, '' ) );
		$chat_id     = esc_attr( (string) get_option( self::OPTION_CHAT_ID, '' ) );
		$test_nonce  = wp_create_nonce( 'cloudscale_telegram_test' );
		$fetch_nonce = wp_create_nonce( 'cloudscale_telegram_fetch' );
		?>
		<div style="border-radius:8px;overflow:hidden;border:1px solid #b3e5fc;">
			<div style="background:linear-gradient(135deg,#0277bd 0%,#039be5 100%);padding:8px 14px;display:flex;align-items:center;gap:8px;">
				<span style="font-size:1rem;">&#9992;</span>
				<span style="color:#fff;font-weight:700;font-size:0.9rem;"><?php echo esc_html__( 'Telegram', $text_domain ); ?></span>
			</div>
			<div style="padding:14px;background:#f0f9ff;">
				<p class="cs-help"><?php echo esc_html__( 'Instant push to your phone. Create a bot via @BotFather on Telegram, then paste the token and your chat ID below.', $text_domain ); ?></p>
				<div style="margin-bottom:6px;">
					<label class="cs-field-label" style="display:block;margin-bottom:3px;"><?php echo esc_html__( 'Bot Token', $text_domain ); ?></label>
					<div style="display:flex;align-items:center;gap:8px;flex-wrap:wrap;">
						<input type="password" id="cs-telegram-token"
						       value="<?php echo $token; ?>"
						       placeholder="123456789:ABCdefGhI..."
						       autocomplete="off" style="width:100%;max-width:300px;padding:4px 8px;height:32px;">
						<button type="button" id="cs-telegram-token-toggle" class="button" style="height:32px;padding:0 10px;font-size:0.82rem;">
							<?php echo esc_html__( 'Show', $text_domain ); ?>
						</button>
					</div>
				</div>
				<div style="margin-bottom:10px;">
					<label class="cs-field-label" style="display:block;margin-bottom:3px;"><?php echo esc_html__( 'Chat ID', $text_domain ); ?></label>
					<div style="display:flex;align-items:center;gap:8px;flex-wrap:wrap;">
						<input type="password" id="cs-telegram-chat-id"
						       value="<?php echo $chat_id; ?>"
						       placeholder="-1001234567890"
						       autocomplete="off" style="width:150px;padding:4px 8px;height:32px;">
						<button type="button" id="cs-telegram-chat-toggle" class="button" style="height:32px;padding:0 10px;font-size:0.82rem;">
							<?php echo esc_html__( 'Show', $text_domain ); ?>
						</button>
						<button type="button" id="cs-telegram-fetch-btn" class="button"
						        data-nonce="<?php echo esc_attr( $fetch_nonce ); ?>">
							<?php echo esc_html__( 'Fetch Chat ID', $text_domain ); ?>
						</button>
					</div>
					<span id="cs-telegram-fetch-msg" style="font-size:0.88rem;display:block;margin-top:4px;"></span>
					<p class="cs-help" style="margin-top:4px;"><?php echo esc_html__( 'Send any message to your bot on Telegram, then click Fetch Chat ID to auto-fill this field.', $text_domain ); ?></p>
				</div>
				<div style="display:flex;align-items:center;gap:8px;">
					<button type="button" id="cs-telegram-test-btn" class="button"
					        data-nonce="<?php echo esc_attr( $test_nonce ); ?>"
					        data-source="<?php echo esc_attr( $source ); ?>">
						<?php echo esc_html__( 'Send Test', $text_domain ); ?>
					</button>
					<span id="cs-telegram-test-msg" style="font-size:0.88rem;"></span>
				</div>
			</div>
		</div>
		<?php if ( ! $js_output ) :
			$js_output = true;
		?>
		<script>
		(function(){
			// Show/Hide toggles
			['cs-telegram-token', 'cs-telegram-chat-id'].forEach(function(inputId) {
				var toggleId = inputId === 'cs-telegram-token' ? 'cs-telegram-token-toggle' : 'cs-telegram-chat-toggle';
				var inp = document.getElementById(inputId);
				var btn = document.getElementById(toggleId);
				if (!inp || !btn) return;
				btn.addEventListener('click', function() {
					var shown = inp.type === 'text';
					inp.type  = shown ? 'password' : 'text';
					btn.textContent = shown ? 'Show' : 'Hide';
				});
			});

			var fetchBtn = document.getElementById('cs-telegram-fetch-btn');
			if (fetchBtn) {
				fetchBtn.addEventListener('click', function(){
					var btn     = this;
					var token   = (document.getElementById('cs-telegram-token').value || '').trim();
					var msg     = document.getElementById('cs-telegram-fetch-msg');
					var chatIn  = document.getElementById('cs-telegram-chat-id');
					if (!token) { msg.textContent = 'Enter bot token first.'; msg.style.color = '#c00'; return; }
					btn.disabled = true;
					msg.textContent = 'Fetching...';
					msg.style.color = '#666';
					var fd = new FormData();
					fd.append('action',          'cloudscale_telegram_fetch_chat_id');
					fd.append('nonce',           btn.dataset.nonce);
					fd.append('telegram_token',  token);
					fetch(ajaxurl, {method:'POST', body:fd})
						.then(function(r){ return r.json(); })
						.then(function(d){
							if (d.success) {
								chatIn.value    = d.data.chat_id;
								msg.textContent = 'Chat ID found: ' + d.data.chat_id;
								msg.style.color = '#0a5';
							} else {
								msg.textContent = d.data || 'Failed.';
								msg.style.color = '#c00';
							}
						})
						.catch(function(){ msg.textContent = 'Request error.'; msg.style.color = '#c00'; })
						.finally(function(){ btn.disabled = false; });
				});
			}

			var testBtn = document.getElementById('cs-telegram-test-btn');
			if (testBtn) {
				testBtn.addEventListener('click', function(){
					var btn = this;
					var msg = document.getElementById('cs-telegram-test-msg');
					btn.disabled = true;
					if (msg) { msg.textContent = 'Sending...'; msg.style.color = '#666'; }
					var fd = new FormData();
					fd.append('action',       'cloudscale_telegram_test');
					fd.append('nonce',        btn.dataset.nonce);
					fd.append('test_source',  btn.dataset.source || '');
					fetch(ajaxurl, {method:'POST', body:fd})
						.then(function(r){ return r.json(); })
						.then(function(d){
							if (msg) {
								msg.textContent = d.success ? (d.data && d.data.msg ? d.data.msg : 'Sent.') : (d.data || 'Failed.');
								msg.style.color = d.success ? '#0a5' : '#c00';
							}
						})
						.catch(function(){ if (msg) { msg.textContent = 'Request error.'; msg.style.color = '#c00'; } })
						.finally(function(){ btn.disabled = false; });
				});
			}
		})();
		</script>
		<?php endif;
	}
}
