<?php
/**
 * Settings page handler.
 *
 * Handles settings save with nonce verification and field sanitization.
 * Pro-only settings are persisted only when the Pro plan is active.
 *
 * @package Waitlytics
 */

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

/**
 * Class WTLY_Settings
 */
class WTLY_Settings {

	/**
	 * Initialize settings hooks.
	 */
	public function init() {
		add_action( 'admin_init', array( $this, 'handle_save' ) );
	}

	/**
	 * Handle settings form submission.
	 */
	public function handle_save() {
		if ( ! isset( $_POST['wtly_save_settings_nonce'] ) ) {
			return;
		}

		if ( ! wp_verify_nonce(
			sanitize_text_field( wp_unslash( $_POST['wtly_save_settings_nonce'] ) ),
			'wtly_save_settings'
		) ) {
			return;
		}

		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			return;
		}

		$settings = $this->sanitize_settings( $_POST );

		update_option( 'wtly_settings', $settings );

		add_settings_error(
			'wtly_settings',
			'wtly_settings_saved',
			__( 'Settings saved.', 'waitlytics' ),
			'updated'
		);
	}

	/**
	 * Sanitize all settings fields by type.
	 *
	 * @param array $input Raw POST data.
	 * @return array Sanitized settings array.
	 */
	private function sanitize_settings( $input ) {
		$clean = array();

		// General.
		$clean['enable_notifications']  = ! empty( $input['enable_notifications'] );
		$clean['guest_subscriptions']   = ! empty( $input['guest_subscriptions'] );
		$clean['show_subscriber_count'] = ! empty( $input['show_subscriber_count'] );

		$allowed_positions = array( 'after_add_to_cart', 'after_summary', 'shortcode' );
		$clean['notification_position'] = isset( $input['notification_position'] ) && in_array( $input['notification_position'], $allowed_positions, true )
			? $input['notification_position']
			: 'after_add_to_cart';

		// Email.
		$clean['email_from_name']             = isset( $input['email_from_name'] ) ? sanitize_text_field( $input['email_from_name'] ) : '';
		$clean['email_from_address']          = isset( $input['email_from_address'] ) ? sanitize_email( $input['email_from_address'] ) : '';
		$clean['email_subject']               = isset( $input['email_subject'] ) ? sanitize_text_field( $input['email_subject'] ) : '';
		$clean['email_heading']               = isset( $input['email_heading'] ) ? sanitize_text_field( $input['email_heading'] ) : '';
		$clean['email_body']                  = isset( $input['email_body'] ) ? wp_kses_post( $input['email_body'] ) : '';
		$clean['email_include_product_image'] = ! empty( $input['email_include_product_image'] );
		$clean['email_include_price']         = ! empty( $input['email_include_price'] );
		$clean['email_include_cta_button']    = ! empty( $input['email_include_cta_button'] );

		// Admin Alerts.
		$clean['admin_notify_new_subscriber'] = ! empty( $input['admin_notify_new_subscriber'] );
		$clean['admin_notify_email']          = isset( $input['admin_notify_email'] ) ? sanitize_email( $input['admin_notify_email'] ) : '';
		$clean['low_stock_threshold']         = isset( $input['low_stock_threshold'] ) ? absint( $input['low_stock_threshold'] ) : 5;
		$clean['admin_low_stock_email']       = ! empty( $input['admin_low_stock_email'] );

		// Form Appearance.
		$clean['form_button_text']    = isset( $input['form_button_text'] ) ? sanitize_text_field( $input['form_button_text'] ) : '';
		$clean['form_success_message'] = isset( $input['form_success_message'] ) ? sanitize_text_field( $input['form_success_message'] ) : '';
		$clean['form_placeholder_text'] = isset( $input['form_placeholder_text'] ) ? sanitize_text_field( $input['form_placeholder_text'] ) : '';

		// Preserve any stored settings keys this class does not manage, so
		// values saved by other builds are carried over untouched.
		$existing = get_option( 'wtly_settings', array() );
		if ( is_array( $existing ) ) {
			foreach ( $existing as $key => $value ) {
				if ( ! array_key_exists( $key, $clean ) ) {
					$clean[ $key ] = $value;
				}
			}
		}

		/**
		 * Filter the sanitized settings before they are saved. The Pro build
		 * uses this to sanitize its own settings fields.
		 *
		 * @param array $clean Sanitized settings.
		 * @param array $input Raw POST data.
		 */
		return apply_filters( 'wtly_sanitize_settings', $clean, $input );
	}
}
