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

class PushoverNotifier extends AbstractNotifier {
	public static function type(): string        { return 'pushover'; }
	public static function label(): string       { return 'Pushover'; }
	public static function description(): string { return 'Mobile push notifications via pushover.net'; }

	public static function config_schema(): array {
		return [
			[ 'key' => 'app_token', 'label' => 'Application API token', 'type' => 'password', 'secret' => true, 'required' => true ],
			[ 'key' => 'user_key',  'label' => 'User key',              'type' => 'password', 'secret' => true, 'required' => true ],
			[ 'key' => 'priority',  'label' => 'Priority',              'type' => 'select',
			  'options' => [ '-2', '-1', '0', '1', '2' ], 'default' => '0',
			  'help'    => '0 = default, 1 = high, 2 = emergency, -1 = quiet, -2 = silent' ],
		];
	}

	public function send( array $config, array $payload ): void {
		$res = wp_remote_post( 'https://api.pushover.net/1/messages.json', [
			'timeout' => 15,
			'body'    => [
				'token'    => $config['app_token'],
				'user'     => $config['user_key'],
				'title'    => $payload['title'],
				'message'  => $payload['message'],
				'priority' => (int) ( $config['priority'] ?? 0 ),
			],
		] );
		if ( is_wp_error( $res ) ) {
			throw new \RuntimeException(  esc_html( $res->get_error_message() )  );
		}
		if ( wp_remote_retrieve_response_code( $res ) >= 400 ) {
			throw new \RuntimeException(  esc_html( 'Pushover: ' . wp_remote_retrieve_body( $res ) )  );
		}
	}
}
