<?php
/**
 * Hub API helpers for maca Hold (shared by REST layer).
 *
 * @package MacaHold
 */

defined( 'ABSPATH' ) || exit;

/**
 * Site key stored by maca Sec Hub reporter.
 *
 * @return string
 */
function maca_hold_hub_get_site_key() {
	return trim( (string) get_option( 'maca_sec_hub_site_key', '' ) );
}

/**
 * Extended feature summary for maca Sec Hub.
 *
 * @return array<string, mixed>
 */
function maca_hold_hub_get_extended_status() {
	$settings     = Maca_Hold_Settings::get();
	$page_ids     = $settings['page_exception_ids'] ?? array();
	$social_links = $settings['social_links'] ?? array();

	if ( ! is_array( $page_ids ) ) {
		$page_ids = array();
	}
	if ( ! is_array( $social_links ) ) {
		$social_links = array();
	}

	return array(
		'page_exception_mode'  => sanitize_key( (string) ( $settings['page_exception_mode'] ?? '' ) ),
		'page_exception_count' => count( $page_ids ),
		'social_links_count'   => count( $social_links ),
		'max_links'            => (int) ( $settings['max_links'] ?? 20 ),
	);
}

/**
 * List WordPress pages available for maintenance exceptions.
 *
 * @return array<int, array{id: int, title: string, slug: string}>
 */
function maca_hold_hub_list_pages() {
	$pages  = get_pages(
		array(
			'sort_column' => 'post_title',
			'sort_order'  => 'ASC',
		)
	);
	$output = array();

	foreach ( $pages as $page ) {
		if ( ! $page instanceof WP_Post ) {
			continue;
		}

		$title = get_the_title( $page );
		if ( ! is_string( $title ) || '' === trim( $title ) ) {
			$title = sprintf(
				/* translators: %d: page ID */
				__( 'Page #%d', 'maca-hold' ),
				(int) $page->ID
			);
		}

		$output[] = array(
			'id'    => (int) $page->ID,
			'title' => $title,
			'slug'  => (string) $page->post_name,
		);
	}

	return $output;
}

/**
 * Map selected page IDs to Hub-friendly rows.
 *
 * @param array<int, int> $page_ids Page IDs.
 * @return array<int, array{id: int, title: string, slug: string}>
 */
function maca_hold_hub_map_page_exceptions( array $page_ids ) {
	$page_ids = array_values(
		array_unique(
			array_filter(
				array_map( 'absint', $page_ids )
			)
		)
	);

	$output = array();

	foreach ( $page_ids as $page_id ) {
		if ( $page_id < 1 || 'page' !== get_post_type( $page_id ) ) {
			continue;
		}

		$title = get_the_title( $page_id );
		if ( ! is_string( $title ) || '' === trim( $title ) ) {
			$title = sprintf(
				/* translators: %d: page ID */
				__( 'Page #%d', 'maca-hold' ),
				$page_id
			);
		}

		$post = get_post( $page_id );

		$output[] = array(
			'id'    => $page_id,
			'title' => $title,
			'slug'  => $post instanceof WP_Post ? (string) $post->post_name : '',
		);
	}

	return $output;
}

/**
 * @return array<string, mixed>
 */
function maca_hold_hub_get_status() {
	$settings  = Maca_Hold_Settings::get();
	$templates = Maca_Hold_Settings::get_templates();
	$template  = Maca_Hold_Settings::sanitize_template( $settings['template'] ?? 'maintenance' );

	$schedule_enabled = ! empty( $settings['schedule_enabled'] );
	$within_schedule  = $schedule_enabled && Maca_Hold_Scheduler::is_within_schedule( $settings );

	$whitelist_raw = (string) ( $settings['ip_whitelist'] ?? '' );
	$whitelist_raw = str_replace( array( "\r\n", "\r" ), "\n", $whitelist_raw );
	$whitelist_lines = array_filter(
		array_map( 'trim', explode( "\n", $whitelist_raw ) ),
		static function ( $line ) {
			return '' !== $line;
		}
	);

	$bypass_roles = $settings['bypass_roles'] ?? array( 'administrator' );
	if ( ! is_array( $bypass_roles ) ) {
		$bypass_roles = array( 'administrator' );
	}

	$page_exception_mode = sanitize_key( (string) ( $settings['page_exception_mode'] ?? '' ) );
	$page_exception_ids  = Maca_Hold_Settings::sanitize( array( 'page_exception_ids' => $settings['page_exception_ids'] ?? array() ) );
	$page_exception_ids  = $page_exception_ids['page_exception_ids'] ?? array();

	$is_active     = Maca_Hold_Settings::is_active();
	$display_scope = Maca_Hold_Maintenance_Scope::get_display_scope();

	return array(
		'installed'           => true,
		'plugin_version'      => defined( 'MACA_HOLD_VERSION' ) ? MACA_HOLD_VERSION : '',
		'is_active'           => $is_active,
		'site_is_public'      => ! $is_active,
		'status_message'      => Maca_Hold_Maintenance_Scope::get_status_text( $display_scope ),
		'scope_effect'        => (string) ( $display_scope['effect'] ?? 'whole_site_public' ),
		'controlled_by'       => $schedule_enabled ? 'schedule' : 'manual',
		'enabled'             => ! empty( $settings['enabled'] ),
		'schedule_enabled'    => $schedule_enabled,
		'schedule_start'      => (string) ( $settings['schedule_start'] ?? '' ),
		'schedule_end'        => (string) ( $settings['schedule_end'] ?? '' ),
		'within_schedule'     => $within_schedule,
		'title'               => (string) ( $settings['title'] ?? '' ),
		'subtitle'            => (string) ( $settings['subtitle'] ?? '' ),
		'page_content_title'  => (string) ( $settings['title'] ?? '' ),
		'page_content_subtitle' => (string) ( $settings['subtitle'] ?? '' ),
		'message'             => (string) ( $settings['message'] ?? '' ),
		'badge_text'          => (string) ( $settings['badge_text'] ?? '' ),
		'countdown_label'     => (string) ( $settings['countdown_label'] ?? '' ),
		'footer_text'         => (string) ( $settings['footer_text'] ?? '' ),
		'logo_url'            => (string) ( $settings['logo_url'] ?? '' ),
		'logo_alt'            => (string) ( $settings['logo_alt'] ?? '' ),
		'template'            => $template,
		'template_label'      => isset( $templates[ $template ] ) ? (string) $templates[ $template ] : $template,
		'background_image'    => (string) ( $settings['background_image'] ?? '' ),
		'background_color'    => (string) ( $settings['background_color'] ?? '' ),
		'text_color'          => (string) ( $settings['text_color'] ?? '' ),
		'accent_color'        => (string) ( $settings['accent_color'] ?? '' ),
		'retry_after'         => (int) ( $settings['retry_after'] ?? 0 ),
		'show_countdown'      => ! empty( $settings['show_countdown'] ),
		'show_login_link'     => ! empty( $settings['show_login_link'] ),
		'login_link_label'    => (string) ( $settings['login_link_label'] ?? '' ),
		'bypass_roles'        => array_values( array_map( 'sanitize_key', $bypass_roles ) ),
		'ip_whitelist_count'  => count( $whitelist_lines ),
		'links_count'         => is_array( $settings['links'] ?? null ) ? count( $settings['links'] ) : 0,
		'page_exception_mode' => $page_exception_mode,
		'page_exception_ids'  => array_values( array_map( 'intval', $page_exception_ids ) ),
		'page_exceptions'     => maca_hold_hub_map_page_exceptions( $page_exception_ids ),
		'extended'            => maca_hold_hub_get_extended_status(),
	);
}

/**
 * Toggle manual maintenance mode (blocked when schedule controls the site).
 *
 * @param bool $enable Whether maintenance should be enabled.
 * @return array<string, mixed>|WP_Error
 */
function maca_hold_hub_toggle_maintenance( $enable ) {
	$settings = Maca_Hold_Settings::get();

	if ( ! empty( $settings['schedule_enabled'] ) ) {
		return new WP_Error(
			'maca_hold_schedule_active',
			__( 'Scheduled maintenance is enabled. Turn off the schedule in settings to use this switch.', 'maca-hold' ),
			array( 'status' => 409 )
		);
	}

	$settings['enabled'] = (bool) $enable;
	Maca_Hold_Settings::update( $settings );

	return array(
		'ok'     => true,
		'status' => maca_hold_hub_get_status(),
	);
}

/**
 * Partial settings update for maca Hub.
 *
 * @param array<string, mixed> $patch Allowed setting keys only.
 * @return array<string, mixed>|WP_Error
 */
function maca_hold_hub_update_settings( array $patch ) {
	$allowed = array(
		'title',
		'subtitle',
		'message',
		'badge_text',
		'footer_text',
		'retry_after',
		'schedule_enabled',
		'schedule_start',
		'schedule_end',
		'show_countdown',
		'show_login_link',
		'login_link_label',
		'page_exception_mode',
		'page_exception_ids',
	);

	$settings    = Maca_Hold_Settings::get();
	$has_changes = false;

	foreach ( $allowed as $key ) {
		if ( ! array_key_exists( $key, $patch ) ) {
			continue;
		}

		$settings[ $key ] = $patch[ $key ];
		$has_changes      = true;
	}

	if ( ! $has_changes ) {
		return new WP_Error(
			'maca_hold_no_changes',
			__( 'No settings to update.', 'maca-hold' ),
			array( 'status' => 400 )
		);
	}

	Maca_Hold_Settings::update( $settings );

	return array(
		'ok'     => true,
		'status' => maca_hold_hub_get_status(),
	);
}
