<?php
/**
 * Business logic service for People & Team schema data
 *
 * Handles author/team member management, team detection, and author box settings.
 *
 * @package BW_Babel
 * @since 3.0.0-babel
 */

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

class BW_Babel_Service_People {

	/**
	 * Prefix for all options (will be bw_babel_* in v3.0.0+)
	 * For now, keeps backward compatibility with bw_schema_*
	 *
	 * @var string
	 */
	const PREFIX = 'bw_schema_'; // TODO: Switch to 'bw_babel_' at v3.0.0-babel release

	// ====== TEAM / AUTHOR CONFIGURATION ======

	/**
	 * Get team post type slug
	 *
	 * @return string Team post type slug or empty string if not configured
	 */
	public static function get_team_post_type() {
		return get_option( self::PREFIX . 'team_post_type', '' );
	}

	/**
	 * Set team post type
	 *
	 * @param string $post_type Team post type slug
	 * @return bool Success
	 */
	public static function set_team_post_type( $post_type ) {
		update_option( self::PREFIX . 'team_post_type', sanitize_key( $post_type ) );
		self::clear_cache();
		return true;
	}

	/**
	 * Check if team/author system is enabled
	 *
	 * @return bool True if team post type is configured
	 */
	public static function is_team_enabled() {
		return ! empty( self::get_team_post_type() );
	}

	/**
	 * Get all team members (published posts of team post type)
	 *
	 * @return array Array of team member WP_Post objects
	 */
	public static function get_team_members() {
		$team_cpt = self::get_team_post_type();
		if ( ! $team_cpt ) {
			return array();
		}

		return get_posts( array(
			'post_type'      => $team_cpt,
			'posts_per_page' => -1,
			'post_status'    => 'publish',
			'orderby'        => 'menu_order',
			'order'          => 'ASC',
		) );
	}

	/**
	 * Get team member count
	 *
	 * @return int Number of published team members
	 */
	public static function get_team_member_count() {
		$team_cpt = self::get_team_post_type();
		if ( ! $team_cpt ) {
			return 0;
		}

		return count_user_posts( 0, $team_cpt, true );
	}

	/**
	 * Get a team member's post object
	 *
	 * @param int $post_id Team member post ID
	 * @return WP_Post|null Team member post or null if not found
	 */
	public static function get_team_member( $post_id ) {
		$post = get_post( $post_id );

		if ( ! $post || $post->post_type !== self::get_team_post_type() ) {
			return null;
		}

		return $post;
	}

	// ====== AUTHOR BOX SETTINGS ======

	/**
	 * Get author box settings
	 *
	 * @return array Author box configuration (enabled, position, post_types)
	 */
	public static function get_author_box_settings() {
		return array(
			'enabled'     => get_option( self::PREFIX . 'author_box_enabled', 'no' ) === 'yes',
			'position'    => get_option( self::PREFIX . 'author_box_position', 'bottom' ),
			'post_types'  => get_option( self::PREFIX . 'author_box_post_types', array() ),
		);
	}

	/**
	 * Update author box settings
	 *
	 * @param array $settings Author box settings
	 * @return bool Success
	 */
	public static function save_author_box_settings( $settings ) {
		update_option( self::PREFIX . 'author_box_enabled', $settings['enabled'] ? 'yes' : 'no' );
		update_option( self::PREFIX . 'author_box_position', sanitize_key( $settings['position'] ?? 'bottom' ) );
		update_option( self::PREFIX . 'author_box_post_types', array_map( 'sanitize_key', $settings['post_types'] ?? array() ) );

		self::clear_cache();
		return true;
	}

	/**
	 * Check if author box is enabled
	 *
	 * @return bool True if author box is enabled
	 */
	public static function is_author_box_enabled() {
		$settings = self::get_author_box_settings();
		return $settings['enabled'];
	}

	/**
	 * Get author box position setting
	 *
	 * @return string Position ('top', 'bottom', or custom)
	 */
	public static function get_author_box_position() {
		$settings = self::get_author_box_settings();
		return $settings['position'];
	}

	/**
	 * Get post types where author box is shown
	 *
	 * @return array Array of post type slugs
	 */
	public static function get_author_box_post_types() {
		$settings = self::get_author_box_settings();
		return $settings['post_types'];
	}

	// ====== AUTHOR ARCHIVE REDIRECT ======

	/**
	 * Check if author archive redirect is enabled
	 *
	 * @return bool True if author archives redirect to team page
	 */
	public static function is_author_redirect_enabled() {
		return get_option( self::PREFIX . 'redirect_author_archives', 'no' ) === 'yes';
	}

	/**
	 * Enable/disable author archive redirect
	 *
	 * @param bool $enabled True to enable
	 * @return bool Success
	 */
	public static function set_author_redirect_enabled( $enabled ) {
		update_option( self::PREFIX . 'redirect_author_archives', $enabled ? 'yes' : 'no' );
		self::clear_cache();
		return true;
	}

	// ====== USER DEFAULT AUTHOR ======

	/**
	 * Get a user's default author/team member
	 *
	 * Used when creating new posts — if set, defaults to this team member.
	 *
	 * @param int $user_id WordPress user ID
	 * @return int Team member post ID or 0 if not set
	 */
	public static function get_user_default_author( $user_id ) {
		return (int) get_user_meta( $user_id, self::PREFIX . 'default_author', true );
	}

	/**
	 * Set a user's default author
	 *
	 * @param int $user_id WordPress user ID
	 * @param int $team_post_id Team member post ID (0 to unset)
	 * @return bool Success
	 */
	public static function set_user_default_author( $user_id, $team_post_id ) {
		$team_post_id = absint( $team_post_id );

		if ( $team_post_id > 0 ) {
			update_user_meta( $user_id, self::PREFIX . 'default_author', $team_post_id );
		} else {
			delete_user_meta( $user_id, self::PREFIX . 'default_author' );
		}

		return true;
	}

	// ====== TEAM DETECTION & ASSIGNMENT ======

	/**
	 * Get all authors associated with a post
	 *
	 * Returns team members detected/assigned to this post.
	 *
	 * @param int $post_id Post ID
	 * @return array Array of team member post IDs
	 */
	public static function get_post_authors( $post_id ) {
		$authors = get_post_meta( $post_id, self::PREFIX . 'authors', true );
		return is_array( $authors ) ? $authors : array();
	}

	/**
	 * Set authors for a post
	 *
	 * @param int   $post_id Post ID
	 * @param array $team_post_ids Array of team member post IDs
	 * @return bool Success
	 */
	public static function set_post_authors( $post_id, $team_post_ids ) {
		if ( empty( $team_post_ids ) ) {
			delete_post_meta( $post_id, self::PREFIX . 'authors' );
		} else {
			update_post_meta( $post_id, self::PREFIX . 'authors', array_map( 'absint', $team_post_ids ) );
		}

		self::clear_post_cache( $post_id );
		return true;
	}

	/**
	 * Get author override for a post
	 *
	 * Allows overriding the team member assigned to a post.
	 *
	 * @param int $post_id Post ID
	 * @return int Team member post ID or 0
	 */
	public static function get_post_author_override( $post_id ) {
		return (int) get_post_meta( $post_id, self::PREFIX . 'author_override', true );
	}

	/**
	 * Set author override for a post
	 *
	 * @param int $post_id Post ID
	 * @param int $team_post_id Team member post ID (0 to clear override)
	 * @return bool Success
	 */
	public static function set_post_author_override( $post_id, $team_post_id ) {
		$team_post_id = absint( $team_post_id );

		if ( $team_post_id > 0 ) {
			update_post_meta( $post_id, self::PREFIX . 'author_override', $team_post_id );
		} else {
			delete_post_meta( $post_id, self::PREFIX . 'author_override' );
		}

		self::clear_post_cache( $post_id );
		return true;
	}

	// ====== HELPERS ======

	/**
	 * Clear related caches
	 *
	 * @return void
	 */
	private static function clear_cache() {
		if ( class_exists( 'BW_Schema_Cache' ) ) {
			BW_Schema_Cache::clear_all();
		}
	}

	/**
	 * Clear cache for a specific post
	 *
	 * @param int $post_id Post ID
	 * @return void
	 */
	private static function clear_post_cache( $post_id ) {
		if ( class_exists( 'BW_Schema_Cache' ) ) {
			BW_Schema_Cache::clear( $post_id );
		}
	}

	/**
	 * Get available position options for author box
	 *
	 * @return array Position key => Label pairs
	 */
	public static function get_position_options() {
		return array(
			'top'    => __( 'Above post content', 'bw-babel' ),
			'bottom' => __( 'Below post content', 'bw-babel' ),
			'side'   => __( 'In sidebar (if available)', 'bw-babel' ),
		);
	}
}
