<?php
/**
 * HVAC Community Events Settings - Refactored
 *
 * Handles plugin settings and configuration
 *
 * @package    HVAC_Community_Events
 * @subpackage Includes
 * @since      1.1.0
 */

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

/**
 * Class HVAC_Settings_Refactored
 */
class HVAC_Settings_Refactored {

	/**
	 * Settings option name
	 *
	 * @var string
	 */
	private $option_name = 'hvac_ce_settings';

	/**
	 * Settings page slug
	 *
	 * @var string
	 */
	private $page_slug = 'hvac-community-events';

	/**
	 * Settings group
	 *
	 * @var string
	 */
	private $settings_group = 'hvac_ce_settings_group';

	/**
	 * Default settings
	 *
	 * @var array
	 */
	private $defaults = array();

	/**
	 * Cached settings
	 *
	 * @var array
	 */
	private $settings = null;

	/**
	 * Constructor
	 */
	public function __construct() {
		$this->set_defaults();
		add_action( 'admin_menu', array( $this, 'add_settings_page' ) );
		add_action( 'admin_init', array( $this, 'register_settings' ) );
	}

	/**
	 * Set default settings
	 */
	private function set_defaults() {
		$this->defaults = array(
			'general' => array(
				'debug_mode' => false,
				'cache_duration' => 300,
				'enable_notifications' => true,
			),
			'registration' => array(
				'auto_approve' => false,
				'require_venue' => false,
				'email_verification' => true,
				'terms_url' => '',
			),
			'dashboard' => array(
				'items_per_page' => 20,
				'show_revenue' => true,
				'show_capacity' => true,
				'date_format' => 'Y-m-d',
			),
			'notifications' => array(
				'admin_email' => get_option( 'admin_email' ),
				'from_email' => get_option( 'admin_email' ),
				'from_name' => get_option( 'blogname' ),
			),
			'advanced' => array(
				'uninstall_data' => false,
				'legacy_support' => false,
			),
		);
	}

	/**
	 * Get all settings
	 *
	 * @return array
	 */
	public function get_settings() {
		if ( null === $this->settings ) {
			$this->settings = get_option( $this->option_name, array() );
			$this->settings = wp_parse_args( $this->settings, $this->defaults );
		}
		return $this->settings;
	}

	/**
	 * Get a specific setting
	 *
	 * @param string $section Setting section
	 * @param string $key     Setting key
	 * @param mixed  $default Default value if not set
	 * @return mixed
	 */
	public function get( $section, $key, $default = null ) {
		$settings = $this->get_settings();
		
		if ( isset( $settings[ $section ][ $key ] ) ) {
			return $settings[ $section ][ $key ];
		}
		
		if ( null !== $default ) {
			return $default;
		}
		
		return isset( $this->defaults[ $section ][ $key ] ) 
			? $this->defaults[ $section ][ $key ] 
			: null;
	}

	/**
	 * Update a setting
	 *
	 * @param string $section Setting section
	 * @param string $key     Setting key
	 * @param mixed  $value   New value
	 * @return bool
	 */
	public function update( $section, $key, $value ) {
		$settings = $this->get_settings();
		
		if ( ! isset( $settings[ $section ] ) ) {
			$settings[ $section ] = array();
		}
		
		$settings[ $section ][ $key ] = $value;
		$this->settings = $settings;
		
		return update_option( $this->option_name, $settings );
	}

	/**
	 * Add settings page to admin menu
	 */
	public function add_settings_page() {
		add_options_page(
			__( 'HVAC Community Events Settings', 'hvac-community-events' ),
			__( 'HVAC Events', 'hvac-community-events' ),
			'manage_options',
			$this->page_slug,
			array( $this, 'render_settings_page' )
		);
	}

	/**
	 * Register settings
	 */
	public function register_settings() {
		register_setting(
			$this->settings_group,
			$this->option_name,
			array( $this, 'sanitize_settings' )
		);

		// General Settings Section
		add_settings_section(
			'hvac_ce_general',
			__( 'General Settings', 'hvac-community-events' ),
			array( $this, 'render_section_general' ),
			$this->page_slug
		);

		add_settings_field(
			'debug_mode',
			__( 'Debug Mode', 'hvac-community-events' ),
			array( $this, 'render_field_checkbox' ),
			$this->page_slug,
			'hvac_ce_general',
			array(
				'label_for' => 'debug_mode',
				'section' => 'general',
				'key' => 'debug_mode',
				'description' => __( 'Enable debug logging', 'hvac-community-events' ),
			)
		);

		add_settings_field(
			'cache_duration',
			__( 'Cache Duration', 'hvac-community-events' ),
			array( $this, 'render_field_number' ),
			$this->page_slug,
			'hvac_ce_general',
			array(
				'label_for' => 'cache_duration',
				'section' => 'general',
				'key' => 'cache_duration',
				'description' => __( 'Cache duration in seconds', 'hvac-community-events' ),
				'min' => 60,
				'max' => 3600,
			)
		);

		// Registration Settings Section
		add_settings_section(
			'hvac_ce_registration',
			__( 'Registration Settings', 'hvac-community-events' ),
			array( $this, 'render_section_registration' ),
			$this->page_slug
		);

		add_settings_field(
			'auto_approve',
			__( 'Auto Approve', 'hvac-community-events' ),
			array( $this, 'render_field_checkbox' ),
			$this->page_slug,
			'hvac_ce_registration',
			array(
				'label_for' => 'auto_approve',
				'section' => 'registration',
				'key' => 'auto_approve',
				'description' => __( 'Automatically approve new trainer registrations', 'hvac-community-events' ),
			)
		);

		// Add more sections and fields as needed
	}

	/**
	 * Render settings page
	 */
	public function render_settings_page() {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		// Show success message if settings were saved
		if ( isset( $_GET['settings-updated'] ) ) {
			add_settings_error(
				'hvac_ce_settings',
				'hvac_ce_settings_message',
				__( 'Settings saved.', 'hvac-community-events' ),
				'updated'
			);
		}

		settings_errors( 'hvac_ce_settings' );
		?>
		<div class="wrap">
			<h1><?php echo esc_html( get_admin_page_title() ); ?></h1>
			<form action="options.php" method="post">
				<?php
				settings_fields( $this->settings_group );
				do_settings_sections( $this->page_slug );
				submit_button( __( 'Save Settings', 'hvac-community-events' ) );
				?>
			</form>
		</div>
		<?php
	}

	/**
	 * Render general section description
	 */
	public function render_section_general() {
		echo '<p>' . __( 'Configure general plugin settings.', 'hvac-community-events' ) . '</p>';
	}

	/**
	 * Render registration section description
	 */
	public function render_section_registration() {
		echo '<p>' . __( 'Configure trainer registration settings.', 'hvac-community-events' ) . '</p>';
	}

	/**
	 * Render checkbox field
	 *
	 * @param array $args Field arguments
	 */
	public function render_field_checkbox( $args ) {
		$value = $this->get( $args['section'], $args['key'] );
		?>
		<input type="checkbox" 
			   id="<?php echo esc_attr( $args['label_for'] ); ?>"
			   name="<?php echo esc_attr( $this->option_name ); ?>[<?php echo esc_attr( $args['section'] ); ?>][<?php echo esc_attr( $args['key'] ); ?>]"
			   value="1"
			   <?php checked( 1, $value, true ); ?>
		/>
		<?php if ( ! empty( $args['description'] ) ) : ?>
			<p class="description"><?php echo esc_html( $args['description'] ); ?></p>
		<?php endif;
	}

	/**
	 * Render number field
	 *
	 * @param array $args Field arguments
	 */
	public function render_field_number( $args ) {
		$value = $this->get( $args['section'], $args['key'] );
		?>
		<input type="number" 
			   id="<?php echo esc_attr( $args['label_for'] ); ?>"
			   name="<?php echo esc_attr( $this->option_name ); ?>[<?php echo esc_attr( $args['section'] ); ?>][<?php echo esc_attr( $args['key'] ); ?>]"
			   value="<?php echo esc_attr( $value ); ?>"
			   min="<?php echo esc_attr( $args['min'] ?? 0 ); ?>"
			   max="<?php echo esc_attr( $args['max'] ?? '' ); ?>"
			   class="regular-text"
		/>
		<?php if ( ! empty( $args['description'] ) ) : ?>
			<p class="description"><?php echo esc_html( $args['description'] ); ?></p>
		<?php endif;
	}

	/**
	 * Render text field
	 *
	 * @param array $args Field arguments
	 */
	public function render_field_text( $args ) {
		$value = $this->get( $args['section'], $args['key'] );
		?>
		<input type="text" 
			   id="<?php echo esc_attr( $args['label_for'] ); ?>"
			   name="<?php echo esc_attr( $this->option_name ); ?>[<?php echo esc_attr( $args['section'] ); ?>][<?php echo esc_attr( $args['key'] ); ?>]"
			   value="<?php echo esc_attr( $value ); ?>"
			   class="regular-text"
		/>
		<?php if ( ! empty( $args['description'] ) ) : ?>
			<p class="description"><?php echo esc_html( $args['description'] ); ?></p>
		<?php endif;
	}

	/**
	 * Sanitize settings
	 *
	 * @param array $input Raw input data
	 * @return array Sanitized data
	 */
	public function sanitize_settings( $input ) {
		$sanitized = array();

		// General settings
		if ( isset( $input['general'] ) ) {
			$sanitized['general'] = array(
				'debug_mode' => ! empty( $input['general']['debug_mode'] ),
				'cache_duration' => absint( $input['general']['cache_duration'] ?? 300 ),
				'enable_notifications' => ! empty( $input['general']['enable_notifications'] ),
			);

			// Update debug mode in logger
			HVAC_Logger::set_enabled( $sanitized['general']['debug_mode'] );
		}

		// Registration settings
		if ( isset( $input['registration'] ) ) {
			$sanitized['registration'] = array(
				'auto_approve' => ! empty( $input['registration']['auto_approve'] ),
				'require_venue' => ! empty( $input['registration']['require_venue'] ),
				'email_verification' => ! empty( $input['registration']['email_verification'] ),
				'terms_url' => esc_url_raw( $input['registration']['terms_url'] ?? '' ),
			);
		}

		// Dashboard settings
		if ( isset( $input['dashboard'] ) ) {
			$sanitized['dashboard'] = array(
				'items_per_page' => absint( $input['dashboard']['items_per_page'] ?? 20 ),
				'show_revenue' => ! empty( $input['dashboard']['show_revenue'] ),
				'show_capacity' => ! empty( $input['dashboard']['show_capacity'] ),
				'date_format' => sanitize_text_field( $input['dashboard']['date_format'] ?? 'Y-m-d' ),
			);
		}

		// Merge with existing settings to preserve sections not being updated
		$existing = $this->get_settings();
		$sanitized = wp_parse_args( $sanitized, $existing );

		return $sanitized;
	}

	/**
	 * Get instance of settings class (singleton)
	 *
	 * @return self
	 */
	public static function get_instance() {
		static $instance = null;
		
		if ( null === $instance ) {
			$instance = new self();
		}
		
		return $instance;
	}
}