<?php
/**
 * Posts sync failure alerts to a Slack incoming webhook.
 *
 * @package StoreSheet
 */

declare( strict_types=1 );

namespace StoreSheet\Notifications;

defined( 'ABSPATH' ) || exit;

class SlackNotifier {

	public function notify( string $hook, string $error_message ): void {
		$settings    = get_option( 'storesheet_settings', array() );
		$webhook_url = $settings['slack_webhook_url'] ?? '';

		if ( empty( $webhook_url ) ) {
			return;
		}

		$site = get_bloginfo( 'name' );
		$url  = get_bloginfo( 'url' );
		$time = current_time( 'Y-m-d H:i:s' );

		$payload = array(
			'text'   => sprintf( ':x: *[StoreSheet] Sync failure* on _%s_', $site ),
			'blocks' => array(
				array(
					'type' => 'section',
					'text' => array(
						'type' => 'mrkdwn',
						'text' => sprintf(
							":x: *StoreSheet sync failure*\n*Site:* <%s|%s>\n*Hook:* `%s`\n*Error:* %s\n*Time:* %s",
							$url,
							$site,
							$hook,
							$error_message,
							$time
						),
					),
				),
			),
		);

		wp_remote_post(
			$webhook_url,
			array(
				'body'      => (string) wp_json_encode( $payload ),
				'headers'   => array( 'Content-Type' => 'application/json' ),
				'timeout'   => 10,
				'blocking'  => false, // fire-and-forget; don't slow down the queue runner
				'sslverify' => true,
			)
		);
	}

	/**
	 * Post the daily digest summary to Slack. Fire-and-forget.
	 *
	 * @since 1.2.0
	 * @param array<string,mixed> $summary Canonical digest summary.
	 */
	public function digest( array $summary ): void {
		$settings    = get_option( 'storesheet_settings', array() );
		$webhook_url = $settings['slack_webhook_url'] ?? '';

		if ( empty( $webhook_url ) ) {
			return;
		}

		$site         = get_bloginfo( 'name' );
		$url          = get_bloginfo( 'url' );
		$time         = current_time( 'Y-m-d H:i:s' );
		$total_failed = (int) ( $summary['total_failed'] ?? 0 );
		$icon         = 0 === $total_failed ? ':white_check_mark:' : ':warning:';

		$labels = array(
			'product' => 'Products',
			'order'   => 'Orders',
			'coupon'  => 'Coupons',
		);

		$lines = array();
		foreach ( $labels as $key => $label ) {
			$resource = $summary['resources'][ $key ] ?? array();
			$lines[]  = sprintf(
				'*%s:* %d synced, %d failed',
				$label,
				(int) ( $resource['success'] ?? 0 ),
				(int) ( $resource['failed'] ?? 0 )
			);
		}

		$payload = array(
			'text'   => sprintf( '%s *[StoreSheet] Daily digest* on _%s_', $icon, $site ),
			'blocks' => array(
				array(
					'type' => 'section',
					'text' => array(
						'type' => 'mrkdwn',
						'text' => sprintf(
							"%s *StoreSheet daily digest*\n*Site:* <%s|%s>\n%s\n*Total:* %d synced, %d failed\n*Time:* %s",
							$icon,
							$url,
							$site,
							implode( "\n", $lines ),
							(int) ( $summary['total'] ?? 0 ),
							$total_failed,
							$time
						),
					),
				),
			),
		);

		wp_remote_post(
			$webhook_url,
			array(
				'body'      => (string) wp_json_encode( $payload ),
				'headers'   => array( 'Content-Type' => 'application/json' ),
				'timeout'   => 10,
				'blocking'  => false, // fire-and-forget; a Slack failure must never block the digest job
				'sslverify' => true,
			)
		);
	}
}
