<?php
/**
 * Admin Settings Class
 *
 * Handles the plugin settings page in the WordPress admin.
 * Manages access control settings and other plugin configuration.
 *
 * @package    Karate_Club_Manager
 * @subpackage Karate_Club_Manager/includes/admin
 * @since      1.0.0
 */

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

/**
 * KCM Admin Settings Class
 *
 * Displays and manages plugin settings in the WordPress admin.
 *
 * @since 1.0.0
 */
class MACM_Admin_Settings {

	/**
	 * Initialize the class and set up hooks.
	 *
	 * @since 1.0.0
	 */
	public function __construct() {
		add_action( 'admin_init', array( $this, 'register_settings' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
	}

	/**
	 * Register plugin settings.
	 *
	 * @since 1.0.0
	 */
	public function register_settings() {
		// Settings registration can be added here if needed.
		// Page Access Control has its own dedicated admin page.
	}


	/**
	 * Enqueue admin scripts and styles.
	 *
	 * @since 1.0.0
	 * @param string $hook The current admin page hook.
	 */
	public function enqueue_scripts( $hook ) {
		// Only load on our settings page.
		if ( 'martial-arts_page_kcm-settings' !== $hook ) {
			return;
		}

		// Enqueue WordPress color picker.
		wp_enqueue_style( 'wp-color-picker' );

		// Enqueue custom admin settings styles.
		wp_enqueue_style(
			'kcm-admin-settings',
			plugins_url( 'assets/css/admin-settings.css', dirname( __DIR__ ) ),
			array(),
			MACM_VERSION
		);

		// Enqueue custom admin settings scripts.
		wp_enqueue_script(
			'kcm-admin-settings',
			plugins_url( 'assets/js/admin-settings.js', dirname( __DIR__ ) ),
			array( 'jquery', 'wp-color-picker' ),
			MACM_VERSION,
			true
		);

		wp_localize_script(
			'kcm-admin-settings',
			'macmSettings',
			array(
				'i18n' => array(
					/* translators: %s: comma-separated list of member names */
					'enterEmailFor'         => __( 'Please enter an email address for: %s', 'martial-arts-club-manager' ),
					/* translators: %d: number of members */
					'confirmCreateAccounts' => __( 'Create WordPress user accounts for %d member(s)? Login credentials will be emailed to each member.', 'martial-arts-club-manager' ),
					'createdAccountsFor'    => __( 'Successfully created accounts for: ', 'martial-arts-club-manager' ),
					'linkedToExisting'      => __( 'Linked to existing accounts: ', 'martial-arts-club-manager' ),
					'refreshPage'           => __( 'Refresh Page', 'martial-arts-club-manager' ),
					'errorOccurred'         => __( 'An error occurred.', 'martial-arts-club-manager' ),
					'ajaxError'             => __( 'AJAX error occurred. Please try again.', 'martial-arts-club-manager' ),
				),
			)
		);
	}

	/**
	 * Display the settings page.
	 *
	 * @since 1.0.0
	 */
	public function display_settings_page() {
		// Check user capabilities.
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'martial-arts-club-manager' ) );
		}

		// Build available tabs.
		$tabs = array(
			'general'        => __( 'General', 'martial-arts-club-manager' ),
			'notifications'  => __( 'Notifications', 'martial-arts-club-manager' ),
			'woocommerce'    => __( 'WooCommerce', 'martial-arts-club-manager' ),
			'button-colours' => __( 'Button Colours', 'martial-arts-club-manager' ),
			'user-accounts'  => __( 'User Accounts', 'martial-arts-club-manager' ),
		);

		// Premium-only tabs — only shown when premium files are available.
		$macm_premium_files_exist = file_exists( MACM_PLUGIN_DIR . 'includes/classes/class-macm-location.php' );
		if ( function_exists( 'macm_fs' ) && macm_fs()->can_use_premium_code() && $macm_premium_files_exist ) {
			// Insert after woocommerce tab.
			$position = array_search( 'woocommerce', array_keys( $tabs ), true );
			if ( false !== $position ) {
				$before = array_slice( $tabs, 0, $position + 1, true );
				$after  = array_slice( $tabs, $position + 1, null, true );
				$tabs   = $before
					+ array( 'email' => __( 'Email', 'martial-arts-club-manager' ) )
					+ array( 'email-design' => __( 'Email Design', 'martial-arts-club-manager' ) )
					+ $after;
			}
		}

		/**
		 * Filter settings tabs.
		 *
		 * @since 1.0.0
		 * @param array $tabs Array of tab slug => label pairs.
		 */
		$tabs = apply_filters( 'macm_settings_tabs', $tabs );

		// Get current tab - validate against actual available tabs.
		$macm_current_tab = $this->get_current_settings_tab( array_keys( $tabs ) );

		// Handle form submission - verify nonce before accessing any POST data.
		if ( isset( $_POST['macm_settings_submit'], $_POST['macm_settings_nonce'] ) ) {
			$nonce = sanitize_text_field( wp_unslash( $_POST['macm_settings_nonce'] ) );
			if ( wp_verify_nonce( $nonce, 'macm_save_settings' ) ) {
				$this->handle_form_submission( $macm_current_tab );
			} else {
				add_settings_error(
					'macm_settings',
					'macm_nonce_error',
					__( 'Security check failed. Please try again.', 'martial-arts-club-manager' ),
					'error'
				);
			}
		}

		// Load the settings page template (variables $tabs and $macm_current_tab are passed via scope).
		include MACM_PLUGIN_DIR . 'templates/admin/settings-page.php';
	}

	/**
	 * Get current settings tab from request.
	 *
	 * Uses filter_input for secure parameter access with validation
	 * against the allowlist of tab slugs.
	 *
	 * @since 1.0.209
	 * @param array $allowed_tabs Array of allowed tab slugs.
	 * @return string The validated current tab slug.
	 */
	private function get_current_settings_tab( $allowed_tabs ) {
		// Use filter_input for secure parameter retrieval.
		// FILTER_SANITIZE_FULL_SPECIAL_CHARS handles XSS protection.
		$tab_input = filter_input( INPUT_GET, 'tab', FILTER_SANITIZE_FULL_SPECIAL_CHARS );

		// If no tab specified or empty, return default.
		if ( empty( $tab_input ) ) {
			return 'general';
		}

		// Sanitize to match WordPress key format and validate against allowlist.
		$tab_sanitized = sanitize_key( $tab_input );
		return in_array( $tab_sanitized, $allowed_tabs, true ) ? $tab_sanitized : 'general';
	}

	/**
	 * Handle settings form submission.
	 *
	 * @since 1.0.0
	 * @param string $tab The current settings tab.
	 */
	private function handle_form_submission( $tab ) {
		// Verify nonce.
		$nonce = isset( $_POST['macm_settings_nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['macm_settings_nonce'] ) ) : '';
		if ( ! wp_verify_nonce( $nonce, 'macm_save_settings' ) ) {
			add_settings_error(
				'macm_settings',
				'macm_nonce_error',
				__( 'Security check failed. Please try again.', 'martial-arts-club-manager' ),
				'error'
			);
			return;
		}

		// Handle different tabs.
		switch ( $tab ) {
			case 'general':
				$this->save_general_settings();
				break;

			case 'notifications':
				$this->save_notifications_settings();
				break;

			case 'woocommerce':
				$this->save_woocommerce_settings();
				break;

			case 'email':
				$this->save_email_settings();
				break;

			case 'email-design':
				$this->save_email_design_settings();
				break;

			case 'button-colours':
				$this->save_button_colours_settings();
				break;

			default:
				do_action( 'macm_save_settings_tab_' . $tab );
				break;
		}
	}

	/**
	 * Save general settings.
	 *
	 * @since 1.0.0
	 */
	private function save_general_settings() {
		// Verify nonce (defense in depth - also verified in handle_form_submission).
		$nonce = isset( $_POST['macm_settings_nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['macm_settings_nonce'] ) ) : '';
		if ( ! wp_verify_nonce( $nonce, 'macm_save_settings' ) ) {
			return;
		}

		// Get and sanitize date format.
		$date_format = isset( $_POST['macm_date_format'] ) ? sanitize_text_field( wp_unslash( $_POST['macm_date_format'] ) ) : 'Y-m-d';

		// Get and sanitize time format.
		$time_format = isset( $_POST['macm_time_format'] ) ? sanitize_text_field( wp_unslash( $_POST['macm_time_format'] ) ) : 'H:i';

		// Get and sanitize items per page (5-100).
		$items_per_page = isset( $_POST['macm_items_per_page'] ) ? absint( wp_unslash( $_POST['macm_items_per_page'] ) ) : 20;
		$items_per_page = max( 5, min( 100, $items_per_page ) );

		// Get and sanitize unit system.
		$unit_system = isset( $_POST['macm_unit_system'] ) ? sanitize_text_field( wp_unslash( $_POST['macm_unit_system'] ) ) : 'metric';
		if ( ! in_array( $unit_system, array( 'metric', 'imperial' ), true ) ) {
			$unit_system = 'metric';
		}

		// Update options.
		update_option( 'macm_date_format', $date_format );
		update_option( 'macm_time_format', $time_format );
		update_option( 'macm_items_per_page', $items_per_page );
		update_option( 'macm_unit_system', $unit_system );

		// Add success message.
		add_settings_error(
			'macm_settings',
			'macm_settings_updated',
			__( 'General settings saved successfully.', 'martial-arts-club-manager' ),
			'success'
		);
	}

	/**
	 * Save WooCommerce settings.
	 *
	 * @since 1.0.0
	 */
	private function save_woocommerce_settings() {
		// Verify nonce (defense in depth - also verified in handle_form_submission).
		$nonce = isset( $_POST['macm_settings_nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['macm_settings_nonce'] ) ) : '';
		if ( ! wp_verify_nonce( $nonce, 'macm_save_settings' ) ) {
			return;
		}

		// Get and sanitize member selector text.
		$member_selector_text = isset( $_POST['macm_member_selector_text'] ) ?
			sanitize_text_field( wp_unslash( $_POST['macm_member_selector_text'] ) ) :
			__( 'Select a member for this product', 'martial-arts-club-manager' );

		// Get checkbox values.
		$require_member_selection = isset( $_POST['macm_require_member_selection'] ) ? 'yes' : 'no';
		$show_member_in_cart      = isset( $_POST['macm_show_member_in_cart'] ) ? 'yes' : 'no';
		$show_member_in_checkout  = isset( $_POST['macm_show_member_in_checkout'] ) ? 'yes' : 'no';

		// Update options.
		update_option( 'macm_member_selector_text', $member_selector_text );
		update_option( 'macm_require_member_selection', $require_member_selection );
		update_option( 'macm_show_member_in_cart', $show_member_in_cart );
		update_option( 'macm_show_member_in_checkout', $show_member_in_checkout );

		// Add success message.
		add_settings_error(
			'macm_settings',
			'macm_settings_updated',
			__( 'WooCommerce settings saved successfully.', 'martial-arts-club-manager' ),
			'success'
		);
	}

	/**
	 * Save email settings.
	 *
	 * @since 1.0.0
	 */
	private function save_email_settings() {
		// Verify nonce (defense in depth - also verified in handle_form_submission).
		$nonce = isset( $_POST['macm_settings_nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['macm_settings_nonce'] ) ) : '';
		if ( ! wp_verify_nonce( $nonce, 'macm_save_settings' ) ) {
			return;
		}

		// Get and sanitize from name.
		$email_from_name = isset( $_POST['macm_email_from_name'] ) ?
			sanitize_text_field( wp_unslash( $_POST['macm_email_from_name'] ) ) :
			get_bloginfo( 'name' );

		// Get and sanitize from email.
		$email_from_email = isset( $_POST['macm_email_from_email'] ) ?
			sanitize_email( wp_unslash( $_POST['macm_email_from_email'] ) ) :
			get_option( 'admin_email' );

		// Validate email.
		if ( ! is_email( $email_from_email ) ) {
			add_settings_error(
				'macm_settings',
				'macm_invalid_email',
				__( 'Please enter a valid email address.', 'martial-arts-club-manager' ),
				'error'
			);
			return;
		}

		// Get and sanitize header/footer (allow line breaks).
		$email_header = isset( $_POST['macm_email_header'] ) ?
			sanitize_textarea_field( wp_unslash( $_POST['macm_email_header'] ) ) :
			__( 'Thank you for being part of our dojo!', 'martial-arts-club-manager' );

		$email_footer = isset( $_POST['macm_email_footer'] ) ?
			sanitize_textarea_field( wp_unslash( $_POST['macm_email_footer'] ) ) :
			/* translators: %s: site name */ sprintf( __( "Best regards,\n%s Team", 'martial-arts-club-manager' ), get_bloginfo( 'name' ) );

		// Update options.
		update_option( 'macm_email_from_name', $email_from_name );
		update_option( 'macm_email_from_email', $email_from_email );
		update_option( 'macm_email_header', $email_header );
		update_option( 'macm_email_footer', $email_footer );

		// Add success message.
		add_settings_error(
			'macm_settings',
			'macm_settings_updated',
			__( 'Email settings saved successfully.', 'martial-arts-club-manager' ),
			'success'
		);
	}

	/**
	 * Save email design settings.
	 *
	 * @since 1.0.59
	 */
	private function save_email_design_settings() {
		// Verify nonce (defense in depth - also verified in handle_form_submission).
		$nonce = isset( $_POST['macm_settings_nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['macm_settings_nonce'] ) ) : '';
		if ( ! wp_verify_nonce( $nonce, 'macm_save_settings' ) ) {
			return;
		}

		// Get and sanitize gradient start color.
		$gradient_start = isset( $_POST['macm_email_gradient_start'] ) ?
			sanitize_hex_color( wp_unslash( $_POST['macm_email_gradient_start'] ) ) :
			'#B11226';

		// Get and sanitize gradient end color.
		$gradient_end = isset( $_POST['macm_email_gradient_end'] ) ?
			sanitize_hex_color( wp_unslash( $_POST['macm_email_gradient_end'] ) ) :
			'#8F0E1E';

		// Validate colors (must be valid hex colors).
		if ( ! $gradient_start || ! preg_match( '/^#[0-9A-Fa-f]{6}$/', $gradient_start ) ) {
			$gradient_start = '#B11226';
		}

		if ( ! $gradient_end || ! preg_match( '/^#[0-9A-Fa-f]{6}$/', $gradient_end ) ) {
			$gradient_end = '#8F0E1E';
		}

		// Update options.
		update_option( 'macm_email_gradient_start', $gradient_start );
		update_option( 'macm_email_gradient_end', $gradient_end );

		// Add success message.
		add_settings_error(
			'macm_settings',
			'macm_settings_updated',
			__( 'Email design settings saved successfully.', 'martial-arts-club-manager' ),
			'success'
		);
	}

	/**
	 * Save button colours settings.
	 *
	 * @since 1.0.71
	 */
	private function save_button_colours_settings() {
		// Verify nonce (defense in depth - also verified in handle_form_submission).
		$nonce = isset( $_POST['macm_settings_nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['macm_settings_nonce'] ) ) : '';
		if ( ! wp_verify_nonce( $nonce, 'macm_save_settings' ) ) {
			return;
		}

		// Get and sanitize gradient start color.
		$button_gradient_start = isset( $_POST['macm_button_gradient_start'] ) ?
			sanitize_hex_color( wp_unslash( $_POST['macm_button_gradient_start'] ) ) :
			'#B11226';

		// Get and sanitize gradient end color.
		$button_gradient_end = isset( $_POST['macm_button_gradient_end'] ) ?
			sanitize_hex_color( wp_unslash( $_POST['macm_button_gradient_end'] ) ) :
			'#8F0E1E';

		// Validate colors (must be valid hex colors).
		if ( ! $button_gradient_start || ! preg_match( '/^#[0-9A-Fa-f]{6}$/', $button_gradient_start ) ) {
			$button_gradient_start = '#B11226';
		}

		if ( ! $button_gradient_end || ! preg_match( '/^#[0-9A-Fa-f]{6}$/', $button_gradient_end ) ) {
			$button_gradient_end = '#8F0E1E';
		}

		// Update options.
		update_option( 'macm_button_gradient_start', $button_gradient_start );
		update_option( 'macm_button_gradient_end', $button_gradient_end );

		// Add success message.
		add_settings_error(
			'macm_settings',
			'macm_settings_updated',
			__( 'Button colour settings saved successfully.', 'martial-arts-club-manager' ),
			'success'
		);
	}

	/**
	 * Save notifications settings.
	 *
	 * @since 1.0.320
	 */
	private function save_notifications_settings() {
		// Verify nonce (defense in depth - also verified in handle_form_submission).
		$nonce = isset( $_POST['macm_settings_nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['macm_settings_nonce'] ) ) : '';
		if ( ! wp_verify_nonce( $nonce, 'macm_save_settings' ) ) {
			return;
		}

		// Get and sanitize notification emails.
		$member_email = isset( $_POST['macm_member_notification_email'] )
			? macm_sanitize_notification_emails( sanitize_text_field( wp_unslash( $_POST['macm_member_notification_email'] ) ) )
			: '';

		$trial_email = isset( $_POST['macm_trial_booking_notification_email'] )
			? macm_sanitize_notification_emails( sanitize_text_field( wp_unslash( $_POST['macm_trial_booking_notification_email'] ) ) )
			: '';

		$events_email = isset( $_POST['macm_events_notification_email'] )
			? macm_sanitize_notification_emails( sanitize_text_field( wp_unslash( $_POST['macm_events_notification_email'] ) ) )
			: '';

		// Update options.
		update_option( 'macm_member_notification_email', $member_email );
		update_option( 'macm_trial_booking_notification_email', $trial_email );
		update_option( 'macm_events_notification_email', $events_email );

		// Add success message.
		add_settings_error(
			'macm_settings',
			'macm_settings_updated',
			__( 'Notification settings saved successfully.', 'martial-arts-club-manager' ),
			'success'
		);
	}
}
