<?php
namespace Barn2\Plugin\Password_Protected_Categories\Admin;

use Barn2\Plugin\Password_Protected_Categories\Dependencies\Lib\Admin\Settings_Util;
use Barn2\Plugin\Password_Protected_Categories\Dependencies\Lib\Registerable;
use Barn2\Plugin\Password_Protected_Categories\Dependencies\Lib\Plugin\Licensed_Plugin;
use Barn2\Plugin\Password_Protected_Categories\Dependencies\Lib\Service\Standard_Service;
use Barn2\Plugin\Password_Protected_Categories\Dependencies\Lib\Admin\Plugin_Promo;
use Barn2\Plugin\Password_Protected_Categories\Dependencies\Lib\Admin\Settings_API_Helper;
use Barn2\Plugin\Password_Protected_Categories\Dependencies\Lib\Plugin\Admin\Admin_Links;
use Barn2\Plugin\Password_Protected_Categories\PPC_Util;

/**
 * This class handles the plugin settings page for Password Protected Categories.
 *
 * @package   Barn2\password-protected-categories
 * @author    Barn2 Plugins <support@barn2.co.uk>
 * @license   GPL-3.0
 * @copyright Barn2 Media Ltd
 */
class Settings_Page implements Registerable, Standard_Service {

	const MENU_SLUG    = 'protected_categories';
	const OPTION_GROUP = 'ppc_main_group';

	private $plugin;
	private $admin_links;
	private $plugin_promo;

	public function __construct( Licensed_Plugin $plugin ) {
		$this->plugin       = $plugin;
		$this->admin_links  = new Admin_Links( $plugin );
		$this->plugin_promo = new Plugin_Promo( $plugin );
	}

	public function register() {
		$this->admin_links->register();
		$this->plugin_promo->register();
		\add_action( 'admin_menu', [ $this, 'add_settings_page' ] );
		\add_action( 'admin_init', [ $this, 'register_settings' ] );
	}

	public function add_settings_page() {
		\add_options_page(
			__( 'Password Protected Categories ', 'password-protected-categories' ),
			__( 'Protected Categories', 'password-protected-categories' ),
			'manage_options',
			self::MENU_SLUG,
			[ $this, 'render_settings_page' ]
		);
	}

	public function render_settings_page() {
		?>
		<div class="wrap">
			<?php do_action( 'barn2_before_plugin_settings', $this->plugin->get_id() ); ?>
			<div class="barn2-settings-inner">
				<h1><?php _e( 'Password Protected Categories', 'password-protected-categories' ); ?></h1>
				<form action="options.php" method="post">
					<?php
					// Output the hidden form fields (_wpnonce, etc)
					\settings_fields( self::OPTION_GROUP );

					// Output the sections and their settings
					\do_settings_sections( self::MENU_SLUG );
					?>
					<p class="submit">
						<input name="Submit" type="submit" name="submit" class="button button-primary" value="<?php \esc_attr_e( 'Save Changes', 'password-protected-categories' ); ?>" />
					</p>
				</form>
			</div>
			<?php do_action( 'barn2_after_plugin_settings', $this->plugin->get_id() ); ?>
		</div>
		<?php
	}

	public function register_settings() {
		\register_setting(
			self::OPTION_GROUP,
			PPC_Util::OPTION_NAME,
			[
				'type'              => 'string', // array type not supported, so just use string
				'description'       => 'Password Protected Categories - options',
				'sanitize_callback' => [ $this, 'save_options' ],
			]
		);

		$license_setting = $this->plugin->get_license_setting();

		// Licence key section
		Settings_API_Helper::add_settings_section(
			'ppc_license',
			self::MENU_SLUG,
			'',
			[ $this, 'settings_page_support_links' ],
			[
				$license_setting->get_license_key_setting(),
				$license_setting->get_license_override_setting(),
			]
		);

		// Main settings section
		$defaults = PPC_Util::default_options();

		Settings_API_Helper::add_settings_section(
			'ppc_protection',
			self::MENU_SLUG,
			'',
			false,
			[
				[
					'id'      => PPC_Util::get_option_name( 'show_protected' ),
					'title'   => __( 'Show protected categories?', 'password-protected-categories' ),
					'type'    => 'checkbox',
					'label'   => __( 'Show protected categories and posts', 'password-protected-categories' ),
					'desc'    => __( 'Tick to show protected categories in public areas of your site (e.g. widgets and navigation menus). Untick to hide them.', 'password-protected-categories' ),
					'default' => $defaults['show_protected'],
				],
			]
		);

		Settings_API_Helper::add_settings_section(
			'ppc_login_form',
			self::MENU_SLUG,
			__( 'Password protected categories', 'password-protected-categories' ),
			[ $this, 'section_description_login_form' ],
			[
				[
					'title'     => __( 'Central login page', 'password-protected-categories' ),
					'desc'      => __( 'Optional: allow users to unlock their category from a central login page. You can also add the password form anywhere using the [category_login] shortcode.', 'password-protected-categories' ),
					'id'        => PPC_Util::get_option_name( 'central_login_page' ),
					'class'     => 'wc-enhanced-select-nostd user-protected',
					'css'       => 'min-width:300px;',
					'type'      => 'select',
					'options'   => PPC_Util::get_pages(),
					'show_page' => PPC_Util::get_central_login_page_id(),
				],
				[
					'id'                => PPC_Util::get_option_name( 'password_expires' ),
					'title'             => __( 'Password expiry', 'password-protected-categories' ),
					'type'              => 'number',
					'desc'              => __( 'How long the category stays unlocked before the password expires.', 'password-protected-categories' ),
					'suffix'            => __( 'days', 'password-protected-categories' ),
					'custom_attributes' => [
						'min' => 1,
					],
					'default'           => $defaults['password_expires'],
				],
				[
					'id'      => PPC_Util::get_option_name( 'form_title' ),
					'title'   => _x( 'Title', 'title for the login page', 'password-protected-categories' ),
					'type'    => 'text',
					'desc'    => __( 'The title of the login page. You can use the placeholder <strong>{title}</strong> to show the name of the current post or category.', 'password-protected-categories' ),
					'default' => $defaults['form_title'],
				],
				[
					'id'      => PPC_Util::get_option_name( 'form_message' ),
					'title'   => __( 'Login message', 'password-protected-categories' ),
					'type'    => 'textarea',
					'desc'    => __( 'The message for the login form. You can use HTML here.', 'password-protected-categories' ),
					'default' => $defaults['form_message'],
					'class'   => 'regular-text',
					'rows'    => 5,
				],
				[
					'id'      => PPC_Util::get_option_name( 'form_label' ),
					'title'   => __( 'Password label', 'password-protected-categories' ),
					'type'    => 'text',
					'desc'    => __( 'The label shown next to the password box.', 'password-protected-categories' ),
					'default' => $defaults['form_label'],
				],
				[
					'id'      => PPC_Util::get_option_name( 'form_label_placeholder' ),
					'title'   => __( 'Use placeholder?', 'password-protected-categories' ),
					'type'    => 'checkbox',
					'label'   => __( 'Use the password label as a placeholder', 'password-protected-categories' ),
					'desc'    => __( 'A placeholder appears inside the box rather than next to it.', 'password-protected-categories' ),
					'default' => $defaults['form_label_placeholder'],
				],
				[
					'id'      => PPC_Util::get_option_name( 'form_button' ),
					'title'   => __( 'Button text', 'password-protected-categories' ),
					'type'    => 'text',
					'desc'    => __( 'The text for the login button.', 'password-protected-categories' ),
					'default' => $defaults['form_button'],
				],
			]
		);

		Settings_API_Helper::add_settings_section(
			'ppc_user_protection',
			self::MENU_SLUG,
			__( 'User and role restricted categories', 'password-protected-categories' ),
			[ $this, 'section_description_user_protection_form' ],
			[
				[
					'id'                => PPC_Util::get_option_name( 'ppc_user_protected' ),
					'title'             => __( 'When logged out', 'password-protected-categories' ),
					'type'              => 'select',
					'desc'              => __( 'What logged out users see when they try to access a category that is protected by role or user.', 'password-protected-categories' ),
					'options'           => [
						'404'     => __( 'Show 404 error', 'password-protected-categories' ),
						'wplogin' => __( 'Show WordPress login page', 'password-protected-categories' ),
						'page'    => __( 'Show custom page', 'password-protected-categories' ),
					],
					'class'             => 'wc-enhanced-select toggle-parent',
					'custom_attributes' => [
						'data-child-class' => 'user-protected',
						'data-toggle-val'  => 'page',
					],
				],
				[
					'id'      => PPC_Util::get_option_name( 'ppc_user_protected_redirect' ),
					'title'   => __( 'Custom page', 'password-protected-categories' ),
					'class'   => 'wc-enhanced-select-nostd user-protected',
					'css'     => 'min-width:300px;',
					'type'    => 'select',
					'options' => PPC_Util::get_pages(),
				],
			]
		);
	}

	public function section_description_login_form() {
		?>
		<p><?php _e( 'Use the settings below to customize the login form displayed on password protected categories and posts.', 'password-protected-categories' ); ?></p>
		<?php
	}

	public function section_description_user_protection_form() {
		?>
		<p><?php _e( 'The following options apply to categories restricted to specific roles and users.', 'password-protected-categories' ); ?></p>
		<?php
	}

	public function settings_page_support_links() {
		?>
		<p>
		<?php
			printf(
				'<p>%s</p><p>%s</p>',
				Settings_Util::get_help_links( $this->plugin ), // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
				''
			);
		?>
			</p>
		<?php
	}

	public function save_options( $options ) {

		$this->plugin->get_license_setting()->save_posted_license_key();

		if ( ! empty( $options['form_message'] ) ) {
			$options['form_message'] = \wp_kses_post( $options['form_message'] );
		}
		if ( ! empty( $options['form_label'] ) ) {
			$options['form_label'] = \wp_strip_all_tags( $options['form_label'] );
		}
		if ( ! empty( $options['form_button'] ) ) {
			$options['form_button'] = \wp_strip_all_tags( $options['form_button'] );
		}
		$options['password_expires'] = \absint( $options['password_expires'] );

		if ( empty( $options['password_expires'] ) ) {
			$defaults                    = PPC_Util::default_options();
			$options['password_expires'] = $defaults['password_expires'];
		}

		if ( isset( $options['central_login_page'] ) ) {
			$old_value = PPC_Util::get_central_login_page_id();
			PPC_Util::save_category_login_page( $options['central_login_page'], $old_value );
		}

		return $options;
	}
}
