<?php
/**
 * Lantern Span People Directory settings screen.
 *
 * @package LanternSpanPeopleDirectory
 */

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

/**
 * Registers and renders Lantern Span People Directory settings.
 */
class LSPD_Settings {

	/**
	 * Option name.
	 *
	 * @var string
	 */
	const OPTION_NAME = 'lspd_settings';

	/**
	 * Registers settings hooks.
	 */
	public function __construct() {
		add_action( 'admin_menu', array( $this, 'add_settings_page' ) );
		add_action( 'admin_init', array( $this, 'register_settings' ) );
		add_filter( 'plugin_action_links_' . plugin_basename( LSPD_FILE ), array( $this, 'filter_plugin_action_links' ) );
	}

	/**
	 * Adds the settings submenu.
	 *
	 * @return void
	 */
	public function add_settings_page() {
		add_submenu_page(
			'edit.php?post_type=' . LSPD_Post_Type::POST_TYPE,
			__( 'Lantern Span People Directory Settings', 'lantern-span-people-directory' ),
			__( 'Settings', 'lantern-span-people-directory' ),
			'manage_options',
			'lspd-settings',
			array( $this, 'render_settings_page' )
		);
	}

	/**
	 * Registers the settings option.
	 *
	 * @return void
	 */
	public function register_settings() {
		register_setting(
			'lspd_settings_group',
			self::OPTION_NAME,
			array(
				'type'              => 'array',
				'sanitize_callback' => array( $this, 'sanitize_settings' ),
				'default'           => array(
					'directory_page_id' => 0,
					'access'            => 'logged_in',
					'per_page'          => 24,
					'sort_by'           => 'last_name',
					'show_alphabet'     => 1,
				),
			)
		);
	}

	/**
	 * Sanitizes submitted settings.
	 *
	 * @param mixed $input Submitted option value.
	 * @return array<string, mixed>
	 */
	public function sanitize_settings( $input ) {
		$current = lspd_get_settings();

		if ( ! is_array( $input ) ) {
			return $current;
		}

		$page_id = isset( $input['directory_page_id'] ) && is_scalar( $input['directory_page_id'] )
			? absint( $input['directory_page_id'] )
			: absint( $current['directory_page_id'] );

		if ( $page_id > 0 && 'page' !== get_post_type( $page_id ) ) {
			$page_id = absint( $current['directory_page_id'] );
		}

		$access = isset( $input['access'] ) && is_string( $input['access'] )
			? sanitize_key( $input['access'] )
			: $current['access'];

		if ( ! in_array( $access, array( 'logged_in', 'public' ), true ) ) {
			$access = $current['access'];
		}

		$per_page = isset( $input['per_page'] ) && is_scalar( $input['per_page'] )
			? absint( $input['per_page'] )
			: absint( $current['per_page'] );

		if ( ! in_array( $per_page, array( 12, 24, 36, 48 ), true ) ) {
			$per_page = absint( $current['per_page'] );
		}

		$sort_by = isset( $input['sort_by'] ) && is_string( $input['sort_by'] )
			? sanitize_key( $input['sort_by'] )
			: $current['sort_by'];

		if ( ! in_array( $sort_by, array( 'first_name', 'last_name' ), true ) ) {
			$sort_by = $current['sort_by'];
		}

		$show_alphabet = isset( $input['show_alphabet'] ) && is_scalar( $input['show_alphabet'] )
			? absint( $input['show_alphabet'] )
			: absint( $current['show_alphabet'] );

		return array(
			'directory_page_id' => $page_id,
			'access'            => $access,
			'per_page'          => $per_page,
			'sort_by'           => $sort_by,
			'show_alphabet'     => $show_alphabet > 0 ? 1 : 0,
		);
	}

	/**
	 * Renders the settings page.
	 *
	 * @return void
	 */
	public function render_settings_page() {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		$settings = lspd_get_settings();
		$pro_url  = lspd_get_pro_url();
		?>
		<div class="wrap lspd-settings-wrap">
			<div class="lspd-settings-brand">
				<img class="lspd-settings-brand__logo" src="<?php echo esc_url( LSPD_URL . 'assets/images/lspd-wordmark.png' ); ?>" width="900" height="180" alt="<?php echo esc_attr__( 'Lantern Span People Directory', 'lantern-span-people-directory' ); ?>">
				<div class="lspd-settings-brand__copy">
					<h1><?php esc_html_e( 'Directory Settings', 'lantern-span-people-directory' ); ?></h1>
					<p><?php esc_html_e( 'Control where the directory appears, how profiles are organized, and who can view them.', 'lantern-span-people-directory' ); ?></p>
				</div>
			</div>

			<?php settings_errors(); ?>

			<div class="lspd-settings-layout">
				<div class="lspd-settings-main">
					<form action="options.php" method="post">
						<?php settings_fields( 'lspd_settings_group' ); ?>

						<div class="lspd-settings-card">
							<h2><?php esc_html_e( 'Directory Display', 'lantern-span-people-directory' ); ?></h2>

							<table class="form-table" role="presentation">
								<tr>
									<th scope="row"><label for="lspd-directory-page"><?php esc_html_e( 'Directory page', 'lantern-span-people-directory' ); ?></label></th>
									<td>
										<?php
										$page_dropdown = wp_dropdown_pages(
											array(
												'name'              => esc_attr( self::OPTION_NAME . '[directory_page_id]' ),
												'id'                => 'lspd-directory-page',
												'selected'          => absint( $settings['directory_page_id'] ),
												'show_option_none'  => esc_html__( 'Select a page', 'lantern-span-people-directory' ),
												'option_none_value' => 0,
												'echo'              => 0,
											)
										);

										if ( is_string( $page_dropdown ) ) {
											echo wp_kses(
												$page_dropdown,
												array(
													'select' => array(
														'aria-describedby' => true,
														'class'            => true,
														'id'               => true,
														'name'             => true,
														'required'         => true,
													),
													'option' => array(
														'class'    => true,
														'disabled' => true,
														'selected' => true,
														'value'    => true,
													),
												)
											);
										}
										?>
										<p class="description"><?php esc_html_e( 'Lantern Span People Directory creates a Directory page during activation. A different page can be selected here.', 'lantern-span-people-directory' ); ?></p>
									</td>
								</tr>

								<tr>
									<th scope="row"><?php esc_html_e( 'Directory access', 'lantern-span-people-directory' ); ?></th>
									<td>
										<fieldset>
											<label>
												<input type="radio" name="<?php echo esc_attr( self::OPTION_NAME ); ?>[access]" value="logged_in" <?php checked( $settings['access'], 'logged_in' ); ?>>
												<?php esc_html_e( 'Logged-in WordPress users only', 'lantern-span-people-directory' ); ?>
											</label><br>
											<label>
												<input type="radio" name="<?php echo esc_attr( self::OPTION_NAME ); ?>[access]" value="public" <?php checked( $settings['access'], 'public' ); ?>>
												<?php esc_html_e( 'Public visitors', 'lantern-span-people-directory' ); ?>
											</label>
											<p class="description lspd-privacy-warning"><?php esc_html_e( 'Public mode displays the saved directory information for every published profile. Add only information you have permission to share.', 'lantern-span-people-directory' ); ?></p>
										</fieldset>
									</td>
								</tr>

								<tr>
									<th scope="row"><label for="lspd-sort-by"><?php esc_html_e( 'Alphabetize directory by', 'lantern-span-people-directory' ); ?></label></th>
									<td>
										<select id="lspd-sort-by" name="<?php echo esc_attr( self::OPTION_NAME ); ?>[sort_by]">
											<option value="last_name" <?php selected( $settings['sort_by'], 'last_name' ); ?>><?php esc_html_e( 'Last name', 'lantern-span-people-directory' ); ?></option>
											<option value="first_name" <?php selected( $settings['sort_by'], 'first_name' ); ?>><?php esc_html_e( 'First name', 'lantern-span-people-directory' ); ?></option>
										</select>
										<p class="description"><?php esc_html_e( 'This controls card order and, when enabled below, the A–Z navigation and letter headings. Names remain displayed exactly as entered.', 'lantern-span-people-directory' ); ?></p>
									</td>
								</tr>

								<tr>
									<th scope="row"><?php esc_html_e( 'A–Z organization', 'lantern-span-people-directory' ); ?></th>
									<td>
										<input type="hidden" name="<?php echo esc_attr( self::OPTION_NAME ); ?>[show_alphabet]" value="0">
										<label for="lspd-show-alphabet">
											<input id="lspd-show-alphabet" type="checkbox" name="<?php echo esc_attr( self::OPTION_NAME ); ?>[show_alphabet]" value="1" <?php checked( ! empty( $settings['show_alphabet'] ) ); ?>>
											<?php esc_html_e( 'Show the A–Z navigation and group profiles beneath letter headings', 'lantern-span-people-directory' ); ?>
										</label>
										<p class="description"><?php esc_html_e( 'Turn this off to display one continuous grid that is still sorted by the selected first-name or last-name order.', 'lantern-span-people-directory' ); ?></p>
									</td>
								</tr>

								<tr>
									<th scope="row"><?php esc_html_e( 'Card layout', 'lantern-span-people-directory' ); ?></th>
									<td>
										<strong><?php esc_html_e( 'Responsive horizontal cards', 'lantern-span-people-directory' ); ?></strong>
										<p class="description"><?php esc_html_e( 'Lantern Span People Directory displays two cards per row on wide screens, changes to one card per row when space is limited, and stacks the photo above the details on phones.', 'lantern-span-people-directory' ); ?></p>
									</td>
								</tr>

								<tr>
									<th scope="row"><label for="lspd-per-page"><?php esc_html_e( 'Profiles per page', 'lantern-span-people-directory' ); ?></label></th>
									<td>
										<select id="lspd-per-page" name="<?php echo esc_attr( self::OPTION_NAME ); ?>[per_page]">
											<?php foreach ( array( 12, 24, 36, 48 ) as $per_page ) : ?>
												<option value="<?php echo esc_attr( $per_page ); ?>" <?php selected( $settings['per_page'], $per_page ); ?>><?php echo esc_html( $per_page ); ?></option>
											<?php endforeach; ?>
										</select>
									</td>
								</tr>
							</table>

							<?php submit_button( __( 'Save Settings', 'lantern-span-people-directory' ) ); ?>
						</div>
					</form>

					<div class="lspd-settings-card">
						<h2><?php esc_html_e( 'Place the Directory', 'lantern-span-people-directory' ); ?></h2>
						<p><?php esc_html_e( 'Use the Lantern Span People Directory block in the block editor, or place this shortcode on any page:', 'lantern-span-people-directory' ); ?></p>
						<p><code>[lantern_span_people_directory]</code></p>
						<p><?php esc_html_e( 'Optional shortcode example:', 'lantern-span-people-directory' ); ?></p>
						<p><code>[lantern_span_people_directory per_page=&quot;36&quot; sort_by=&quot;last_name&quot;]</code></p>
					</div>
				</div>

				<aside class="lspd-settings-sidebar">
					<div class="lspd-settings-card lspd-data-card">
						<h2><?php esc_html_e( 'Your Directory Data', 'lantern-span-people-directory' ); ?></h2>
						<p><?php esc_html_e( 'Profiles and photos remain in your WordPress installation. Lantern Span People Directory does not require an external account or service.', 'lantern-span-people-directory' ); ?></p>
						<p><?php esc_html_e( 'The directory is restricted to logged-in users by default. Review access and privacy choices before publishing personal contact information.', 'lantern-span-people-directory' ); ?></p>
					</div>

					<?php if ( '' !== $pro_url ) : ?>
						<div class="lspd-settings-card lspd-pro-card">
							<h2><?php esc_html_e( 'Lantern Span People Directory Pro', 'lantern-span-people-directory' ); ?></h2>
							<p><?php esc_html_e( 'Add households, stronger privacy controls, self-service updates, multiple directories, PDF tools, imports, and reports.', 'lantern-span-people-directory' ); ?></p>
							<p><a class="button button-primary" href="<?php echo esc_url( $pro_url ); ?>"><?php esc_html_e( 'Explore Lantern Span People Directory Pro', 'lantern-span-people-directory' ); ?></a></p>
						</div>
					<?php endif; ?>

					<div class="lspd-settings-card lspd-version-card">
						<p><strong><?php esc_html_e( 'Lantern Span People Directory', 'lantern-span-people-directory' ); ?></strong> <?php echo esc_html( LSPD_VERSION ); ?></p>
					</div>
				</aside>
			</div>
		</div>
		<?php
	}

	/**
	 * Adds settings and, when configured, Pro links to the Plugins screen.
	 *
	 * @param array<int, string> $links Existing plugin links.
	 * @return array<int, string>
	 */
	public function filter_plugin_action_links( $links ) {
		$settings_url = admin_url( 'edit.php?post_type=' . LSPD_Post_Type::POST_TYPE . '&page=lspd-settings' );
		$settings     = '<a href="' . esc_url( $settings_url ) . '">' . esc_html__( 'Settings', 'lantern-span-people-directory' ) . '</a>';

		array_unshift( $links, $settings );

		$pro_url = lspd_get_pro_url();

		if ( '' !== $pro_url ) {
			$links[] = '<a href="' . esc_url( $pro_url ) . '">' . esc_html__( 'Upgrade to Pro', 'lantern-span-people-directory' ) . '</a>';
		}

		return $links;
	}
}
