<?php
/**
 * Review Request Email Settings.
 *
 * Stores and retrieves the scheduler configuration for the review request email:
 * target audience, send delay, and the "skip already reviewed" option.
 *
 * @package Ugcify\Email
 */

namespace Ugcify\Email;

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class ReviewRequestSettings
 */
class ReviewRequestSettings {

	/**
	 * Option key for review request settings.
	 *
	 * @var string
	 */
	const OPTION = 'ugcify_review_request_settings';

	/**
	 * Valid audience values.
	 *
	 * @var string[]
	 */
	private static $valid_audience = array( 'woo_customers', 'wp_users' );

	/**
	 * Get default settings.
	 *
	 * @return array
	 */
	public static function get_defaults() {
		return array(
			'audience'         => array( 'woo_customers' ),
			'delay_days'       => 7,
			'exclude_reviewed' => true,
		);
	}

	/**
	 * Get settings merged with defaults.
	 *
	 * @return array
	 */
	public static function get() {
		$saved = get_option( self::OPTION, array() );
		if ( ! is_array( $saved ) ) {
			$saved = array();
		}

		$merged = wp_parse_args( $saved, self::get_defaults() );

		// Ensure audience is always an array.
		if ( ! is_array( $merged['audience'] ) ) {
			$merged['audience'] = self::get_defaults()['audience'];
		}

		return $merged;
	}

	/**
	 * Save review request settings.
	 *
	 * @param array $data Raw input data.
	 * @return bool
	 */
	public static function save( array $data ) {
		$audience = array_values(
			array_filter(
				(array) ( $data['audience'] ?? array() ),
				static function ( $a ) {
					return in_array( $a, array( 'woo_customers', 'wp_users' ), true );
				}
			)
		);

		$sanitized = array(
			'audience'         => $audience,
			'delay_days'       => max( 0, absint( $data['delay_days'] ?? 7 ) ),
			'exclude_reviewed' => (bool) ( $data['exclude_reviewed'] ?? true ),
		);

		// update_option() returns false when the value is unchanged — that is not an error.
		update_option( self::OPTION, $sanitized );
		return true;
	}
}
