<?php
class UM_Gallery_Settings {

	private $options;

	/**
	 * Option key, and option page slug
	 *
	 * @var string
	 */
	private $key = 'um_gallery';

	/**
	 * Option key, and option page slug
	 *
	 * @var string
	 */
	private $setting_key = 'um_gallery';

	/**
	 * Options page metabox id
	 *
	 * @var string
	 */
	private $metabox_id = 'um_gallery_pro';

	/**
	 * Options Page title
	 *
	 * @var string
	 */
	protected $title = '';

	/**
	 * Options Page hook
	 *
	 * @var string
	 */
	protected $options_page = '';

	private $fields = array();

	/**
	 * Active Tab
	 *
	 * @var string
	 */
	public $active_tab = '';

	public function __construct( $init_hooks = false ) {
		if ( $init_hooks ) {
			// Set our title
			$this->title      = __( 'UM Gallery', 'gallery-for-ultimate-member' );
			$this->active_tab = ( isset( $_GET['tab'] ) && ! empty( $_GET['tab'] ) ? esc_attr( $_GET['tab'] ) : 'general' );

			// add_action('admin_menu', array($this, 'add_admin_menu'));
			add_action( 'admin_init', array( $this, 'page_init' ) );
			add_action( 'admin_init', array( $this, 'handle_option_page_submission' ) );
			add_action( 'um_gallery_after_options_page', array( $this, 'add_admin_menu' ), 10, 1 );
		}
	}

	public function add_admin_menu( $page_key = '' ) {
		add_submenu_page(
			$page_key,
			__( 'Settings', 'gallery-for-ultimate-member' ),
			__( 'Settings', 'gallery-for-ultimate-member' ),
			'manage_options',
			$this->setting_key,
			array( $this, 'create_admin_page' )
		);
	}

	public function get_settings_fields() {
		$options = array();
		$fields  = array();

		if ( function_exists( 'UM' ) ) {
			$fields['general'][] = array(
				'name'    => __( 'Allowed User Roles', 'gallery-for-ultimate-member' ),
				'id'      => 'allowed_roles',
				'type'    => 'multicheck',
				'options' => function_exists( 'UM' ) ? UM()->roles()->get_roles() : array(),
			);
		}

		$fields['general'][] = array(
			'id'      => 'um_gallery_profile',
			'type'    => 'radio_inline',
			'name'    => __( 'Show on Main Tab', 'gallery-for-ultimate-member' ),
			'default' => 'on',
			'desc'    => __( 'If enabled, recent photo uploads will be placed on a user\'s profile main tab', 'gallery-for-ultimate-member' ),
			'options' => array(
				'on'  => __( 'Yes', 'gallery-for-ultimate-member' ),
				'off' => __( 'No', 'gallery-for-ultimate-member' ),
			),
		);

		$fields['general'][] = array(
			'id'      => 'um_gallery_cropped_images',
			'type'    => 'radio_inline',
			'name'    => __( 'Disable thumbnails', 'gallery-for-ultimate-member' ),
			'default' => 'off',
			'desc'    => __( 'Use full images instead of cropped thumbnails', 'gallery-for-ultimate-member' ),
			'options' => array(
				'on'  => __( 'Yes', 'gallery-for-ultimate-member' ),
				'off' => __( 'No', 'gallery-for-ultimate-member' ),
			),
		);

		$fields['labels'][] = array(
			'id'      => 'um_gallery_tab_name',
			'type'    => 'text',
			'name'    => __( 'Tab Name', 'gallery-for-ultimate-member' ),
			'default' => __( 'Gallery', 'gallery-for-ultimate-member' ),
		);

		$fields['labels'][] = array(
			'id'      => 'um_gallery_tab_slug',
			'type'    => 'text',
			'name'    => __( 'Tab Slug', 'gallery-for-ultimate-member' ),
			'desc'    => __( 'Slug that displays in URL', 'gallery-for-ultimate-member' ),
			'default' => __( 'gallery', 'gallery-for-ultimate-member' ),
		);

		$fields['labels'][] = array(
			'id'      => 'um_gallery_tab_icon',
			'type'    => 'text',
			'name'    => __( 'Tab Icon', 'gallery-for-ultimate-member' ),
			'desc'    => __( 'Icon displayed in profile tab', 'gallery-for-ultimate-member' ),
			'default' => 'um-faicon-camera',
		);

		$fields['labels'][] = array(
			'id'      => 'um_gallery_default_album_name',
			'type'    => 'text',
			'name'    => __( 'Default Album Name', 'gallery-for-ultimate-member' ),
			'desc'    => __( 'Give each album a custom name in single album mode. Use the shortcode [username] or [user_id] to give each album something unique.', 'gallery-for-ultimate-member' ),
			'default' => __( 'Album by [user_id]', 'gallery-for-ultimate-member' ),
		);

		$fields['labels'][] = array(
			'id'      => 'um_gallery_add_photo_btn',
			'type'    => 'text',
			'name'    => __( 'Add Photo Button Text', 'gallery-for-ultimate-member' ),
			'desc'    => __( 'Displays in single album mode', 'gallery-for-ultimate-member' ),
			'default' => __( 'Add Photo', 'gallery-for-ultimate-member' ),
		);

		$fields['labels'][] = array(
			'id'      => 'um_gallery_modal_title',
			'type'    => 'text',
			'name'    => __( 'Manage Album Title', 'gallery-for-ultimate-member' ),
			'desc'    => __( 'Displays above modal popup', 'gallery-for-ultimate-member' ),
			'default' => __( 'Manage Album', 'gallery-for-ultimate-member' ),
		);

		$fields['labels'][] = array(
			'id'      => 'um_gallery_add_photos_tab',
			'type'    => 'text',
			'name'    => __( 'Add Photos', 'gallery-for-ultimate-member' ),
			'desc'    => __( 'Photos Tab inside Modal Uploader', 'gallery-for-ultimate-member' ),
			'default' => __( 'Add Photos', 'gallery-for-ultimate-member' ),
		);

		$fields['labels'][] = array(
			'id'      => 'um_gallery_add_videos_tab',
			'type'    => 'text',
			'name'    => __( 'Add Videos', 'gallery-for-ultimate-member' ),
			'desc'    => __( 'Videos Tab inside Modal Uploader', 'gallery-for-ultimate-member' ),
			'default' => __( 'Add Videos', 'gallery-for-ultimate-member' ),
		);

		$fields['labels'][] = array(
			'id'      => 'um_gallery_upload_photos_text',
			'type'    => 'text',
			'name'    => __( 'Upload your photos placeholder', 'gallery-for-ultimate-member' ),
			'desc'    => __( 'Text inside modal photos upload screen', 'gallery-for-ultimate-member' ),
			'default' => __( 'Upload your photos', 'gallery-for-ultimate-member' ),
		);

		$fields['labels'][] = array(
			'id'      => 'um_gallery_video_placeholder_text',
			'type'    => 'text',
			'name'    => __( 'Video URL Placeholder', 'gallery-for-ultimate-member' ),
			'desc'    => __( 'Placeholder text inside of video uploader field', 'gallery-for-ultimate-member' ),
			'default' => __( 'Video URL', 'gallery-for-ultimate-member' ),
		);

		$fields['labels'][] = array(
			'id'      => 'um_gallery_add_video_button',
			'type'    => 'text',
			'name'    => __( 'Add Video Button Text', 'gallery-for-ultimate-member' ),
			'desc'    => __( 'Text inside of video add button', 'gallery-for-ultimate-member' ),
			'default' => __( 'Add Video', 'gallery-for-ultimate-member' ),
		);

		$fields['labels'][] = array(
			'id'      => 'um_gallery_save_button',
			'type'    => 'text',
			'name'    => __( 'Save Button', 'gallery-for-ultimate-member' ),
			'desc'    => __( 'Save button inside of modal photos uploader', 'gallery-for-ultimate-member' ),
			'default' => __( 'Save', 'gallery-for-ultimate-member' ),
		);

		$fields['labels'][] = array(
			'id'      => 'um_gallery_cancel_button',
			'type'    => 'text',
			'name'    => __( 'Cancel Button', 'gallery-for-ultimate-member' ),
			'desc'    => __( 'Cancel button inside of modal photos uploader', 'gallery-for-ultimate-member' ),
			'default' => __( 'Cancel', 'gallery-for-ultimate-member' ),
		);

		$fields['layout'][] = array(
			'id'   => 'main_tab_header',
			'type' => 'gheader',
			'name' => __( 'Gallery Tab', 'gallery-for-ultimate-member' ),
		);

		$fields['layout'][] = array(
			'id'      => 'um_gallery_profile_count',
			'type'    => 'text',
			'name'    => __( 'Photos on profile', 'gallery-for-ultimate-member' ),
			'desc'    => __( 'Set the number of photos on profile', 'gallery-for-ultimate-member' ),
			'default' => 10,
		);

		$fields['layout'][] = array(
			'id'      => 'um_gallery_tab',
			'type'    => 'radio_inline',
			'name'    => __( 'Show Gallery Tab', 'gallery-for-ultimate-member' ),
			'default' => 'off',
			'desc'    => __( 'If enabled, a gallery tab will be placed on a user\'s profile page', 'gallery-for-ultimate-member' ),
			'options' => array(
				'on'  => __( 'Yes', 'gallery-for-ultimate-member' ),
				'off' => __( 'No', 'gallery-for-ultimate-member' ),
			),
		);

		$fields['layout'][] = array(
			'id'   => 'main_profile_header',
			'type' => 'gheader',
			'name' => __( 'Main/Profile Tab', 'gallery-for-ultimate-member' ),
		);

		$fields['layout'][] = array(
			'id'          => 'um_main_gallery_type',
			'type'        => 'select',
			'select2'     => array(
				'allowClear'              => 0,
				'minimumResultsForSearch' => -1,
			),
			'name'        => __( 'Profile Layout Type', 'gallery-for-ultimate-member' ),
			'desc'        => __( 'Select the type of layout for gallery on gallery tab', 'gallery-for-ultimate-member' ),
			'default'     => 'grid',
			'options'     => array(
				'carousel'  => __( 'Carousel', 'gallery-for-ultimate-member' ),
				'grid'      => __( 'Grid', 'gallery-for-ultimate-member' ),
				'slideshow' => __( 'Slideshow', 'gallery-for-ultimate-member' ),
			),
			'placeholder' => __( 'Choose layout...', 'gallery-for-ultimate-member' ),
		);

		$fields['layout'][] = array(
			'id'          => 'carousel_setting',
			'type'        => 'gheader',
			'name'        => __( 'Carousel/Slideshow settings', 'gallery-for-ultimate-member' ),
			'description' => __( 'Changed the settings used by the Carousel or Slideshow below.', 'gallery-for-ultimate-member' ),
		);

		$fields['layout'][] = array(
			'id'      => 'um_gallery_carousel_item_count',
			'type'    => 'text',
			'name'    => __( 'Number of items in Carousel', 'gallery-for-ultimate-member' ),
			'desc'    => __( 'Set the number of photos to display in Carousel', 'gallery-for-ultimate-member' ),
			'default' => 10,
		);

		$fields['layout'][] = array(
			'id'      => 'um_gallery_seconds_count',
			'type'    => 'text',
			'name'    => __( 'Number of seconds for Autoplay', 'gallery-for-ultimate-member' ),
			'desc'    => __( 'Set the Slideshow/Carousel Autoplay in seconds', 'gallery-for-ultimate-member' ),
			'default' => 0,
		);

		$fields['layout'][] = array(
			'id'      => 'um_gallery_autoplay',
			'type'    => 'radio_inline',
			'name'    => __( 'AutoPlay Slideshow/Carousel', 'gallery-for-ultimate-member' ),
			'default' => 'off',
			'desc'    => __( 'If enabled, the gallery will auto play on a user\'s profile page', 'gallery-for-ultimate-member' ),
			'options' => array(
				'on'  => __( 'Yes', 'gallery-for-ultimate-member' ),
				'off' => __( 'No', 'gallery-for-ultimate-member' ),
			),
		);

		$fields['layout'][] = array(
			'id'      => 'um_gallery_pagination',
			'type'    => 'radio_inline',
			'name'    => __( 'Turn Pagination On', 'gallery-for-ultimate-member' ),
			'default' => 'off',
			'desc'    => __( 'Enable this to display Pagination', 'gallery-for-ultimate-member' ),
			'options' => array(
				'on'  => __( 'Yes', 'gallery-for-ultimate-member' ),
				'off' => __( 'No', 'gallery-for-ultimate-member' ),
			),
		);

		$fields['layout'][] = array(
			'id'      => 'um_gallery_autoheight',
			'type'    => 'radio_inline',
			'name'    => __( 'Turn AutoHeight On', 'gallery-for-ultimate-member' ),
			'default' => 'off',
			'desc'    => __( 'Enable this to turn AutoHeight on', 'gallery-for-ultimate-member' ),
			'options' => array(
				'on'  => __( 'Yes', 'gallery-for-ultimate-member' ),
				'off' => __( 'No', 'gallery-for-ultimate-member' ),
			),
		);

		$fields['layout'][] = array(
			'id'   => 'mischeader',
			'type' => 'gheader',
			'name' => __( 'Other', 'gallery-for-ultimate-member' ),
		);

		$fields['layout'][] = array(
			'id'      => 'um_gallery_fullscreen',
			'type'    => 'radio_inline',
			'name'    => __( 'Show full screen button', 'gallery-for-ultimate-member' ),
			'default' => 'on',
			'desc'    => __( 'Enable this to show the fullscreen button', 'gallery-for-ultimate-member' ),
			'options' => array(
				'on'  => __( 'Yes', 'gallery-for-ultimate-member' ),
				'off' => __( 'No', 'gallery-for-ultimate-member' ),
			),
		);

		$fields['layout'][] = array(
			'id'      => 'close_modal_save',
			'type'    => 'radio_inline',
			'name'    => __( 'Close Modal after update', 'gallery-for-ultimate-member' ),
			'default' => 'off',
			'desc'    => __( 'Enable this to close modal after an album is updated or after files and videos have been added.', 'gallery-for-ultimate-member' ),
			'options' => array(
				'on'  => __( 'Yes', 'gallery-for-ultimate-member' ),
				'off' => __( 'No', 'gallery-for-ultimate-member' ),
			),
		);

		return apply_filters( 'um_gallery_options', $fields );
	}

	/**
	 * Outputs nonce, action, and option_page fields for a settings page.
	 *
	 * @since 2.7.0
	 *
	 * @param string $option_group A settings group name. This should match the group name
	 *                             used in register_setting().
	 */
	private function settings_fields( $option_group ) {
		echo "<input type='hidden' name='option_page' value='" . esc_attr( $option_group ) . "' />";
		echo '<input type="hidden" name="action" value="update_gallery_settings" />';
		wp_nonce_field( "$option_group-options" );
	}
	public function create_admin_page() {
		$active_tab    = $this->active_tab;
		$this->options = $this->um_gallery_settings();
		?>
		<div class="wrap">
			<h2><?php echo esc_html( 'UM Gallery Settings', 'gallery-for-ultimate-member' ); ?></h2>
			<h2 class="nav-tab-wrapper">
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=' . $this->setting_key . '&tab=general' ) ); ?>" class="nav-tab <?php echo ( 'general' == $active_tab ? 'nav-tab-active' : '' ); ?>"><?php esc_html_e( 'General', 'gallery-for-ultimate-member' ); ?></a>
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=' . $this->setting_key . '&tab=layout' ) ); ?>" class="nav-tab <?php echo 'layout' == $active_tab ? 'nav-tab-active' : ''; ?>"><?php esc_html_e( 'Layout', 'gallery-for-ultimate-member' ); ?></a>
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=' . $this->setting_key . '&tab=labels' ) ); ?>" class="nav-tab <?php echo 'labels' == $active_tab ? 'nav-tab-active' : ''; ?>"><?php esc_html_e( 'Labels', 'gallery-for-ultimate-member' ); ?></a>
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=' . $this->setting_key . '&tab=addons' ) ); ?>" class="nav-tab <?php echo ( 'addons' == $active_tab ? 'nav-tab-active' : '' ); ?>"><?php esc_html_e( 'Addons', 'gallery-for-ultimate-member' ); ?></a>
			</h2>
			<?php if ( 'addons' == $active_tab ) : ?>
				<?php do_action( 'um_gallery_action_tab' ); ?>
			<?php else : ?>
				<form method="post" action="<?php admin_url( 'admin.php?page=' . $this->setting_key ); ?>">
					<?php
					$this->settings_fields( 'um_gallery_option_group' );
					do_settings_sections( 'um_gallery' );
					submit_button();
					?>
				</form>
			<?php endif; ?>
		</div>
		<?php
	}

	public function page_init() {
		register_setting(
			'um_gallery_option_group',
			'um_gallery',
			array( $this, 'sanitize' )
		);

		add_settings_section(
			'um_gallery', // ID
			null,
			'__return_false',
			$this->key // Page
		);

		// do_action( 'um_gallery_fields_init' );
		$this->fields = $this->get_settings_fields();
		if ( ! empty( $this->fields[ $this->active_tab ] ) ) {
			foreach ( $this->fields[ $this->active_tab ] as $field_args ) {
				$defaults = array(
					'id'      => '',
					'name'    => '',
					'type'    => 'text',
					'default' => '',
					'desc'    => '',
					'options' => array(),
				);

				$args = wp_parse_args( $field_args, $defaults );
				$this->add_settings_field( $this->key, $args['id'], $args['name'], $args['type'], $args['options'], $args['default'] );
			}
		}
	}

	public function sanitize( $input ) {
		$new_input = array();
		// Sanitize input data here

		return $input;
	}

	private function add_settings_field( $section_id, $id, $title, $type, $options = array(), $default = '' ) {
		add_settings_field(
			$id,
			$title,
			array( $this, 'field_callback' ),
			$section_id,
			$section_id,
			array(
				'id'      => $id,
				'type'    => $type,
				'name'    => $title,
				'options' => $options,
				'default' => $default,
			)
		);
	}

	public function field_callback( $args ) {
		$type         = $args['type'];
		$id           = $args['id'];
		$options      = isset( $args['options'] ) ? $args['options'] : '';
		$default      = isset( $args['default'] ) ? $args['default'] : '';
		$option_value = isset( $this->options[ $id ] ) ? $this->options[ $id ] : array();
		switch ( $type ) {
			case 'text':
				printf(
					'<input type="text" id="%s" name="um_gallery_options[%s]" value="%s" />',
					esc_attr( $id ),
					esc_attr( $id ),
					isset( $this->options[ $id ] ) ? esc_attr( $this->options[ $id ] ) : esc_html( $default )
				);
				break;

			case 'radio_inline':
				if ( ! empty( $options ) ) {
					print( '<ul class="um-gallery-inline-radio">' );
					foreach ( $options as $key => $label ) {
						printf(
							'<li><label><input type="radio" name="um_gallery_options[%s]" value="%s" %s /> %s</label></li>',
							esc_attr( $id ),
							esc_attr( $key ),
							isset( $this->options[ $id ] ) && $this->options[ $id ] === $key ? 'checked' : esc_html( $default ),
							esc_html( $label )
						);
					}
					print_r( '</ul>' );
				}
				break;

			case 'select':
				if ( ! empty( $options ) ) {
					printf( '<select id="%s" name="um_gallery_options[%s]">', esc_attr( $id ), esc_attr( $id ) );
					foreach ( $options as $value => $label ) {
						printf(
							'<option value="%s" %s>%s</option>',
							esc_attr( $value ),
							isset( $this->options[ $id ] ) && $this->options[ $id ] == $value ? 'selected' : esc_html( $default ),
							esc_html( $label )
						);
					}
					printf( '</select>' );
				}
				break;
			case 'gheader':
				if ( ! empty( $args['name'] ) ) {
					// echo '<h2>' . esc_html($args['name']) . '</h2>';
				}
				break;
			case 'multicheck':
				if ( ! empty( $options ) ) {
					foreach ( $options as $key => $label ) {
						$checked = in_array( $key, $option_value ) ? 'checked="checked"' : '';
						printf(
							'<label><input type="checkbox" name="um_gallery_options[%s][]' . '" value="%s" %s /> %s</label><br>',
							esc_attr( $id ),
							esc_attr( $key ),
							esc_html( $checked ),
							esc_html( $label )
						);
					}
				}
				break;

			// ... Add cases for other field types as needed
		}
	}

	private function um_gallery_settings() {
		$options = um_gallery_settings();
		return $options;
	}

	private function get_value_from_section( $id = '', $key = '', $fields = array() ) {
		if ( ! empty( $fields ) ) {
			foreach ( $fields as $row ) {
				if ( $row['id'] == $id ) {
					return $row[ $key ];
				}
			}
		}
	}
	public function handle_option_page_submission() {
		// Check if the action is 'update'
		if ( isset( $_POST['action'] ) && $_POST['action'] == 'update_gallery_settings' ) {

			// Verify nonce to improve security (recommended)
			if ( isset( $_POST['_wpnonce'] ) && wp_verify_nonce( $_POST['_wpnonce'], 'um_gallery_option_group-options' ) ) {
				// Process and save the submitted data
				$options       = $this->um_gallery_settings();
				$input         = ! empty( $_POST['um_gallery_options'] ) ? $_POST['um_gallery_options'] : array();
				$doing_section = ! empty( $_POST['_wp_http_referer'] );
				$tab           = '';
				if ( true === $doing_section ) {
					// Pull out the tab and section
					parse_str( $_POST['_wp_http_referer'], $referrer );
					$tab = ! empty( $referrer['tab'] ) ? sanitize_key( $referrer['tab'] ) : 'general';
				}

				$section_data = $type = $this->fields[ $tab ];
				$option_set   = array();
				if ( ! empty( $input ) ) {
					foreach ( $input as $key => $value ) {
						$type = $this->get_value_from_section( $key, 'type', $section_data );
						switch ( $type ) {
							case 'text':
							case 'radio_inline':
							case 'select':
								$option_set[ $key ] = sanitize_text_field( $value );
								break;
							case 'multicheck':
								$multi_check_vals = array();
								if ( ! empty( $value ) && is_array( $value ) ) {
									foreach ( $value as $v ) {
										$multi_check_vals[] = sanitize_text_field( $v );
									}
								}
								$option_set[ $key ] = $multi_check_vals;
								break;
							default:
								$option_set[ $key ] = sanitize_text_field( $value );
						}
					}
				}
				$output = array_merge( $options, $option_set );
				update_option( $this->key, $output );

				// Redirect to the options page after processing
				$redirect_url = admin_url( 'admin.php?page=um_gallery' );
				if ( $tab ) {
					$redirect_url = add_query_arg( 'tab', $tab, $redirect_url );
				}
				wp_safe_redirect( $redirect_url );
				exit();
			}
		}
	}
}

if ( is_admin() ) {
	new UM_Gallery_Settings( true );
}
