<?php
/**
 * Base class for senders in the Automation Web Platform.
 *
 * @package automation-web-platform
 */

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

/**
 * Abstract class WAWP_Sender_Base
 *
 * @package automation-web-platform
 */
abstract class WAWP_Sender_Base {
	use WAWP_Settings_Handler;
	use WAWP_Logging_Trait;

	/**
	 * Aliasing the trait method to avoid naming conflicts.
	 */
	use WAWP_Security_Trait {
		check_permissions as trait_check_permissions;
	}

	/**
	 * Main WAWP Instance.
	 *
	 * @var WAWP
	 */
	protected $wawp;

	/**
	 * Database Manager.
	 *
	 * @var WAWP_Database_Manager
	 */
	protected $db;

	/**
	 * Connector Service.
	 *
	 * @var WAWP_Connector
	 */
	protected $connector;

	/**
	 * Parent instance.
	 *
	 * @var mixed
	 */
	protected $parent;

	/**
	 * Nonce action for security checks.
	 *
	 * @var string
	 */
	protected $nonce_action;

	/**
	 * Constructor.
	 *
	 * @param mixed $parent_sender Parent object or manager.
	 */
	public function __construct( $parent_sender = null ) {
		$this->wawp      = WAWP::instance();
		$this->db        = $this->wawp->db;
		$this->connector = $this->wawp->connector;
		$this->parent    = $parent_sender;
		$this->setup_properties();
	}

	/**
	 * Setup class properties.
	 */
	abstract protected function setup_properties();

	/**
	 * Permissions check delegating to the security trait.
	 *
	 * @param string $nonce_action Nonce action.
	 * @param string $nonce_field  Nonce field name.
	 */
	protected function check_permissions( $nonce_action = '', $nonce_field = 'nonce' ) {
		$action = ! empty( $nonce_action ) ? $nonce_action : $this->nonce_action;
		$this->trait_check_permissions( $action, $nonce_field );
	}



	/**
	 * Shared helper to update multiple options.
	 *
	 * @param array $options_map Map of POST keys to option names.
	 */
	protected function update_options_from_post( $options_map ) {
		foreach ( $options_map as $post_key => $option_name ) {
			$val = filter_input( INPUT_POST, $post_key, FILTER_DEFAULT );
			if ( null !== $val ) {
				$this->update_wawp_setting( $option_name, is_array( $val ) ? array_map( 'sanitize_text_field', $val ) : sanitize_text_field( $val ) );
			}
		}
	}

	/**
	 * Shared helper to update multiple options from an associative array.
	 *
	 * @param array $settings Settings array.
	 */
	protected function update_options( $settings ) {
		foreach ( $settings as $key => $value ) {
			$this->update_wawp_setting( $key, $value );
		}
	}
}
