<?php
/**
 * Directory profile administration screens and fields.
 *
 * @package LanternSpanPeopleDirectory
 */

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

/**
 * Manages the WordPress administration experience for directory profiles.
 */
class LSPD_Admin {

	/**
	 * Registers administration hooks.
	 */
	public function __construct() {
		add_action( 'add_meta_boxes_' . LSPD_Post_Type::POST_TYPE, array( $this, 'add_meta_boxes' ) );
		add_action( 'save_post_' . LSPD_Post_Type::POST_TYPE, array( $this, 'save_member_details' ), 10, 2 );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_assets' ) );
		add_action( 'admin_init', array( 'LSPD_Activator', 'maybe_upgrade' ) );
		add_action( 'admin_notices', array( $this, 'show_admin_notices' ) );
		add_filter( 'manage_' . LSPD_Post_Type::POST_TYPE . '_posts_columns', array( $this, 'filter_member_columns' ) );
		add_action( 'manage_' . LSPD_Post_Type::POST_TYPE . '_posts_custom_column', array( $this, 'render_member_column' ), 10, 2 );
		add_filter( 'post_row_actions', array( $this, 'filter_member_row_actions' ), 10, 2 );
	}

	/**
	 * Adds the profile contact-information meta box.
	 *
	 * @return void
	 */
	public function add_meta_boxes() {
		add_meta_box(
			'lspd-member-details',
			__( 'Directory Information', 'lantern-span-people-directory' ),
			array( $this, 'render_member_details_meta_box' ),
			LSPD_Post_Type::POST_TYPE,
			'normal',
			'high'
		);
	}

	/**
	 * Renders the profile details meta box.
	 *
	 * @param WP_Post $post Current profile post.
	 * @return void
	 */
	public function render_member_details_meta_box( $post ) {
		$role    = get_post_meta( $post->ID, '_lspd_role', true );
		$email   = get_post_meta( $post->ID, '_lspd_email', true );
		$phone   = get_post_meta( $post->ID, '_lspd_phone', true );
		$address = get_post_meta( $post->ID, '_lspd_address', true );

		$role    = is_string( $role ) ? $role : '';
		$email   = is_string( $email ) ? $email : '';
		$phone   = is_string( $phone ) ? $phone : '';
		$address = is_string( $address ) ? $address : '';

		wp_nonce_field( 'lspd_save_person_details', 'lspd_person_details_nonce' );
		?>
		<div class="lspd-admin-fields">
			<p>
				<label for="lspd_role"><strong><?php esc_html_e( 'Role or title', 'lantern-span-people-directory' ); ?></strong></label>
				<input type="text" class="widefat" id="lspd_role" name="lspd_role" value="<?php echo esc_attr( $role ); ?>" maxlength="190">
				<span class="description"><?php esc_html_e( 'Examples: Manager, Pastor, Board Member, Treasurer, Volunteer, or Team Member.', 'lantern-span-people-directory' ); ?></span>
			</p>

			<div class="lspd-admin-fields__row">
				<p>
					<label for="lspd_email"><strong><?php esc_html_e( 'Email address', 'lantern-span-people-directory' ); ?></strong></label>
					<input type="email" class="widefat" id="lspd_email" name="lspd_email" value="<?php echo esc_attr( $email ); ?>" maxlength="190">
				</p>

				<p>
					<label for="lspd_phone"><strong><?php esc_html_e( 'Phone number', 'lantern-span-people-directory' ); ?></strong></label>
					<input type="tel" class="widefat" id="lspd_phone" name="lspd_phone" value="<?php echo esc_attr( $phone ); ?>" maxlength="80">
				</p>
			</div>

			<p>
				<label for="lspd_address"><strong><?php esc_html_e( 'Address', 'lantern-span-people-directory' ); ?></strong></label>
				<textarea class="widefat" id="lspd_address" name="lspd_address" rows="4"><?php echo esc_textarea( $address ); ?></textarea>
			</p>

			<p class="description">
				<?php esc_html_e( 'Use the WordPress editor for a biography or other information. Long biographies are supported. Use the Profile Photo panel to upload the person’s picture.', 'lantern-span-people-directory' ); ?>
			</p>
		</div>
		<?php
	}

	/**
	 * Saves the profile details meta box.
	 *
	 * @param int     $post_id Current post ID.
	 * @param WP_Post $post    Current post.
	 * @return void
	 */
	public function save_member_details( $post_id, $post ) {
		if ( ! isset( $_POST['lspd_person_details_nonce'] ) || ! is_string( $_POST['lspd_person_details_nonce'] ) ) {
			return;
		}

		$nonce = sanitize_text_field( wp_unslash( $_POST['lspd_person_details_nonce'] ) );

		if ( ! wp_verify_nonce( $nonce, 'lspd_save_person_details' ) ) {
			return;
		}

		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
			return;
		}

		if ( wp_is_post_revision( $post_id ) ) {
			return;
		}

		if ( ! ( $post instanceof WP_Post ) || LSPD_Post_Type::POST_TYPE !== $post->post_type ) {
			return;
		}

		if ( ! current_user_can( 'edit_lspd_person', $post_id ) ) {
			return;
		}

		$submitted_fields = array();

		if ( isset( $_POST['lspd_role'] ) && is_string( $_POST['lspd_role'] ) ) {
			$submitted_fields['_lspd_role'] = sanitize_text_field( wp_unslash( $_POST['lspd_role'] ) );
		}

		if ( isset( $_POST['lspd_email'] ) && is_string( $_POST['lspd_email'] ) ) {
			$submitted_fields['_lspd_email'] = sanitize_email( wp_unslash( $_POST['lspd_email'] ) );
		}

		if ( isset( $_POST['lspd_phone'] ) && is_string( $_POST['lspd_phone'] ) ) {
			$submitted_fields['_lspd_phone'] = sanitize_text_field( wp_unslash( $_POST['lspd_phone'] ) );
		}

		if ( isset( $_POST['lspd_address'] ) && is_string( $_POST['lspd_address'] ) ) {
			$submitted_fields['_lspd_address'] = sanitize_textarea_field( wp_unslash( $_POST['lspd_address'] ) );
		}

		foreach ( $submitted_fields as $meta_key => $value ) {
			if ( '' === $value ) {
				delete_post_meta( $post_id, $meta_key );
			} else {
				update_post_meta( $post_id, $meta_key, $value );
			}
		}
	}

	/**
	 * Loads the admin stylesheet only on Lantern Span People Directory screens.
	 *
	 * @param string $hook_suffix Current admin page hook.
	 * @return void
	 */
	public function enqueue_admin_assets( $hook_suffix ) {
		$screen = get_current_screen();

		if ( ! $screen ) {
			return;
		}

		$is_member_screen = isset( $screen->post_type ) && LSPD_Post_Type::POST_TYPE === $screen->post_type;
		$is_settings_page = isset( $screen->id ) && LSPD_Post_Type::POST_TYPE . '_page_lspd-settings' === $screen->id;

		if ( ! $is_member_screen && ! $is_settings_page ) {
			return;
		}

		$stylesheet_path    = LSPD_PATH . 'assets/css/admin.css';
		$stylesheet_version = LSPD_VERSION;

		if ( file_exists( $stylesheet_path ) ) {
			$modified_time = filemtime( $stylesheet_path );

			if ( false !== $modified_time ) {
				$stylesheet_version .= '.' . $modified_time;
			}
		}

		wp_enqueue_style(
			'lspd-admin',
			LSPD_URL . 'assets/css/admin.css',
			array(),
			$stylesheet_version
		);
	}

	/**
	 * Displays a one-time getting-started notice after activation.
	 *
	 * @return void
	 */
	public function show_admin_notices() {
		if ( ! current_user_can( 'edit_lspd_people' ) ) {
			return;
		}

		if ( ! get_transient( 'lspd_activation_notice' ) ) {
			return;
		}

		delete_transient( 'lspd_activation_notice' );

		$add_url      = admin_url( 'post-new.php?post_type=' . LSPD_Post_Type::POST_TYPE );
		$settings_url = admin_url( 'edit.php?post_type=' . LSPD_Post_Type::POST_TYPE . '&page=lspd-settings' );
		?>
		<div class="notice notice-success is-dismissible">
			<p>
				<strong><?php esc_html_e( 'Lantern Span People Directory is ready.', 'lantern-span-people-directory' ); ?></strong>
				<?php esc_html_e( 'Add your first person, then review the directory access setting.', 'lantern-span-people-directory' ); ?>
			</p>
			<p>
				<a class="button button-primary" href="<?php echo esc_url( $add_url ); ?>"><?php esc_html_e( 'Add a Person', 'lantern-span-people-directory' ); ?></a>
				<a class="button" href="<?php echo esc_url( $settings_url ); ?>"><?php esc_html_e( 'Directory Settings', 'lantern-span-people-directory' ); ?></a>
			</p>
		</div>
		<?php
	}

	/**
	 * Adds directory fields to the profile list table.
	 *
	 * @param array<string, string> $columns Existing columns.
	 * @return array<string, string>
	 */
	public function filter_member_columns( $columns ) {
		$updated = array();

		foreach ( $columns as $key => $label ) {
			if ( 'title' === $key ) {
				$updated['lspd_photo'] = __( 'Photo', 'lantern-span-people-directory' );
			}

			$updated[ $key ] = $label;

			if ( 'title' === $key ) {
				$updated['lspd_role']  = __( 'Role', 'lantern-span-people-directory' );
				$updated['lspd_email'] = __( 'Email', 'lantern-span-people-directory' );
				$updated['lspd_phone'] = __( 'Phone', 'lantern-span-people-directory' );
			}
		}

		return $updated;
	}

	/**
	 * Renders custom profile-list columns.
	 *
	 * @param string $column  Column key.
	 * @param int    $post_id Profile post ID.
	 * @return void
	 */
	public function render_member_column( $column, $post_id ) {
		switch ( $column ) {
			case 'lspd_photo':
				if ( has_post_thumbnail( $post_id ) ) {
					echo wp_kses_post(
						get_the_post_thumbnail(
							$post_id,
							array( 56, 56 ),
							array(
								'class' => 'lspd-admin-thumbnail',
								'alt'   => '',
							)
						)
					);
				} else {
					echo '<span aria-hidden="true">—</span><span class="screen-reader-text">' . esc_html__( 'No profile photo', 'lantern-span-people-directory' ) . '</span>';
				}
				break;

			case 'lspd_role':
			case 'lspd_email':
			case 'lspd_phone':
				$meta_keys = array(
					'lspd_role'  => '_lspd_role',
					'lspd_email' => '_lspd_email',
					'lspd_phone' => '_lspd_phone',
				);
				$value = get_post_meta( $post_id, $meta_keys[ $column ], true );

				if ( is_string( $value ) && '' !== $value ) {
					echo esc_html( $value );
				} else {
					echo '<span aria-hidden="true">—</span>';
				}
				break;
		}
	}

	/**
	 * Adds a link from a published profile row to the front-end directory.
	 *
	 * @param array<string, string> $actions Existing row actions.
	 * @param WP_Post              $post    Current post.
	 * @return array<string, string>
	 */
	public function filter_member_row_actions( $actions, $post ) {
		if ( ! ( $post instanceof WP_Post ) || LSPD_Post_Type::POST_TYPE !== $post->post_type || 'publish' !== $post->post_status ) {
			return $actions;
		}

		$url = add_query_arg( 'lspd_person', absint( $post->ID ), lspd_get_directory_url() );

		/* translators: %s: person name. */
		$label = sprintf( __( 'View %s in the directory', 'lantern-span-people-directory' ), get_the_title( $post ) );

		$actions['lspd_view'] = '<a href="' . esc_url( $url ) . '" aria-label="' . esc_attr( $label ) . '">' . esc_html__( 'View in directory', 'lantern-span-people-directory' ) . '</a>';

		return $actions;
	}
}
