<?php
/**
 * Shared TutorHelper email settings.
 *
 * @package TutorHelper_Bookings
 */

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

/**
 * Stores shared Core email sender details.
 */
final class TutorHelper_Email_Settings {

	/**
	 * Stored settings option.
	 *
	 * @var string
	 */
	const OPTION_NAME =
		'tutorhelper_email_settings';

	/**
	 * Return default Core email settings.
	 *
	 * @return array
	 */
	public static function get_defaults() {
		return array(
			'sender_name' =>
				wp_specialchars_decode(
					get_bloginfo( 'name' ),
					ENT_QUOTES
				),

			'contact_email' =>
				sanitize_email(
					get_option(
						'admin_email'
					)
				),

			'privacy_policy_url' =>
				esc_url_raw(
					get_privacy_policy_url()
				),
		);
	}

	/**
	 * Return saved settings with defaults applied.
	 *
	 * @return array
	 */
	public static function get_all() {
		$defaults =
			self::get_defaults();

		$saved =
			get_option(
				self::OPTION_NAME,
				array()
			);

		if ( ! is_array( $saved ) ) {
			$saved = array();
		}

		return wp_parse_args(
			$saved,
			$defaults
		);
	}

	/**
	 * Return one setting.
	 *
	 * @param string $key Setting key.
	 *
	 * @return string
	 */
	public static function get(
		$key
	) {
		$key =
			sanitize_key(
				$key
			);

		$settings =
			self::get_all();

		return isset(
			$settings[ $key ]
		)
			? $settings[ $key ]
			: '';
	}

	/**
	 * Save Core email settings.
	 *
	 * @param array $data Submitted values.
	 *
	 * @return true|WP_Error
	 */
	public static function save(
		$data
	) {
		$data =
			is_array( $data )
				? $data
				: array();

		$sender_name =
			isset(
				$data['sender_name']
			)
				? sanitize_text_field(
					wp_unslash(
						$data['sender_name']
					)
				)
				: '';

		$contact_email =
			isset(
				$data['contact_email']
			)
				? sanitize_email(
					wp_unslash(
						$data[
							'contact_email'
						]
					)
				)
				: '';

		$privacy_policy_url =
			isset(
				$data[
					'privacy_policy_url'
				]
			)
				? esc_url_raw(
					wp_unslash(
						$data[
							'privacy_policy_url'
						]
					)
				)
				: '';

		if ( '' === trim( $sender_name ) ) {
			return new WP_Error(
				'tutorhelper_email_sender_name_missing',
				__(
					'Sender name is required.',
					'tutorhelper-bookings'
				)
			);
		}

		if (
			'' === $contact_email
			|| ! is_email(
				$contact_email
			)
		) {
			return new WP_Error(
				'tutorhelper_email_contact_invalid',
				__(
					'Enter a valid contact email address.',
					'tutorhelper-bookings'
				)
			);
		}

		update_option(
			self::OPTION_NAME,
			array(
				'sender_name' =>
					$sender_name,

				'contact_email' =>
					$contact_email,

				'privacy_policy_url' =>
					$privacy_policy_url,
			),
			false
		);

		return true;
	}
}
