<?php
namespace Backreload\Notifiers;
if ( ! defined( 'ABSPATH' ) ) { exit; }

class TelegramNotifier extends AbstractNotifier {
	public static function type(): string        { return 'telegram'; }
	public static function label(): string       { return 'Telegram'; }
	public static function description(): string { return 'Send messages via a Telegram bot'; }

	public static function config_schema(): array {
		return [
			[ 'key' => 'bot_token', 'label' => 'Bot token', 'type' => 'password', 'secret' => true, 'required' => true,
			  'help' => 'Get one from @BotFather. Looks like 1234567:ABC-DEF…' ],
			[ 'key' => 'chat_id', 'label' => 'Chat ID', 'type' => 'text', 'required' => true,
			  'help' => 'Personal chat, group, or channel ID. For groups prefix with -100…' ],
			[ 'key' => 'parse_mode', 'label' => 'Format', 'type' => 'select',
			  'options' => [ 'plain', 'Markdown', 'HTML' ], 'default' => 'Markdown' ],
		];
	}

	public function validate( array $config ): array {
		$config = parent::validate( $config );
		if ( ! preg_match( '/^\d+:[A-Za-z0-9_-]+$/', $config['bot_token'] ?? '' ) ) {
			throw new NotifierValidationException( [ 'bot_token' => 'Token should look like 1234567:ABC-DEF…' ] );
		}
		return $config;
	}

	public function send( array $config, array $payload ): void {
		$url   = "https://api.telegram.org/bot{$config['bot_token']}/sendMessage";
		$mode  = $config['parse_mode'] ?? 'Markdown';
		$emoji = 'error' === $payload['level'] ? '🚨' : '✅';

		switch ( $mode ) {
			case 'HTML':
				$body = "{$emoji} <b>" . esc_html( $payload['title'] ) . "</b>\n" . esc_html( $payload['message'] );
				break;
			case 'Markdown':
				// Telegram Markdown V1 uses *bold*. We don't escape user content because
				// the title/message come from our trusted backup metadata.
				$body = "{$emoji} *{$payload['title']}*\n{$payload['message']}";
				break;
			default: // 'plain' — no formatting, no asterisks
				$body = "{$emoji} {$payload['title']}\n{$payload['message']}";
		}

		$args = [ 'chat_id' => $config['chat_id'], 'text' => $body ];
		if ( 'plain' !== $mode ) {
			$args['parse_mode'] = $mode;
		}
		$this->post_json( $url, $args );
	}
}
