<?php
/**
 * Generic webhook destination.
 *
 * @package Ordsync
 */

defined( 'ABSPATH' ) || exit;

/**
 * This is the engine's real product. Google Sheets is just a preset on top of it.
 * Works with Make, n8n, Airtable, Slack relays, or anything that accepts JSON.
 */
class Ordsync_Dest_Webhook extends Ordsync_Destination {

	/**
	 * Key.
	 *
	 * @return string
	 */
	public function key() {
		return 'webhook';
	}

	/**
	 * Label.
	 *
	 * @return string
	 */
	public function label() {
		return __( 'Webhook', 'ordercarry-order-automation-for-woocommerce' );
	}

	/**
	 * Enabled and configured.
	 *
	 * @return bool
	 */
	public function is_enabled() {
		return parent::is_enabled() && '' !== $this->setting( 'url' );
	}

	/**
	 * Send.
	 *
	 * @param array $payload Order payload.
	 * @return true|WP_Error
	 */
	public function send( array $payload ) {

		/*
		 * Deliberately NOT Ordsync_Settings::secret(). That one is printed
		 * into every Apps Script and travels to Google in clear; signing
		 * webhooks with it meant anyone who could read a shared sheet could
		 * forge requests to whatever this webhook points at.
		 */
		$secret = Ordsync_Settings::webhook_secret();

		return $this->post(
			$this->setting( 'url' ),
			$payload,
			array(
				'headers' => array(
					'Content-Type'      => 'application/json',
					// Lets the receiver verify the request really came from this store.
					'X-Ordsync-Signature' => hash_hmac( 'sha256', wp_json_encode( $payload ), $secret ),
				),
			)
		);
	}
}
