<?php
/**
 * Trait WAWP_Settings_Handler.
 * Centralizes settings management, migration, and standardization.
 *
 * @package automation-web-platform
 */

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

trait WAWP_Settings_Handler {

	/**
	 * Get a setting from options with fallback to legacy keys.
	 *
	 * @param string      $key New setting key.
	 * @param mixed       $default_value Default value.
	 * @param string|null $legacy_key Optional legacy key to check.
	 * @return mixed
	 */
	public function get_wawp_setting( $key, $default_value = null, $legacy_key = null ) {
		$value = get_option( $key, null );
		if ( ( null === $value || '' === $value ) && null !== $legacy_key ) {
			$value = get_option( $legacy_key, $default_value );

			// Auto-migrate if found.
			if ( $value !== $default_value ) {
				update_option( $key, $value );
			}
		}

		return ( null !== $value && '' !== $value ) ? $value : $default_value;
	}

	/**
	 * Update a setting in the database.
	 *
	 * @param string      $key New setting key.
	 * @param mixed       $value Value to save.
	 * @param string|bool $autoload Whether to autoload the option. Default null (uses native default).
	 * @return bool True if value changed, false if not.
	 */
	public function update_wawp_setting( $key, $value, $autoload = null ) {
		return update_option( $key, $value, $autoload );
	}

	/**
	 * Sanitize and JSON encode settings for database storage.
	 *
	 * @param mixed $value Value to prepare.
	 * @return string Prepared string.
	 */
	public function prepare_for_db( $value ) {
		if ( is_array( $value ) || is_object( $value ) ) {
			return wp_json_encode( $value );
		}

		return (string) $value;
	}

	/**
	 * Decode JSON settings from database.
	 *
	 * @param string $value Value to decode.
	 * @param bool   $assoc Return as associative array.
	 * @return mixed Decoded data.
	 */
	public function from_db( $value, $assoc = true ) {
		if ( empty( $value ) ) {
			return $assoc ? array() : new stdClass();
		}

		if ( is_array( $value ) || is_object( $value ) ) {
			return $value;
		}

		$decoded = json_decode( $value, $assoc );

		return ( JSON_ERROR_NONE === json_last_error() ) ? $decoded : $value;
	}

	/**
	 * Standardize a notification rule data (Example of shared logic).
	 *
	 * @param array $data Notification data.
	 * @return array Standardized data.
	 */
	protected function standardize_notification_data( $data ) {
		$defaults = array(
			'enabled'          => 0,
			'whatsapp_enabled' => 0,
			'email_enabled'    => 0,
			'whatsapp_message' => '',
			'email_subject'    => '',
			'email_body'       => '',
			'sender_type'      => 'user_whatsapp',
		);

		return array_merge( $defaults, (array) $data );
	}
}
