<?php
/**
 * Available Tabs API Endpoint Class
 *
 * Handles REST API endpoints for available tab management.
 *
 * @package RedFoxWP\RedFoxTabManager
 * @since 1.0.0
 */

namespace RedFoxWP\RedFoxTabManager\API;

use RedFoxWP\RedFoxTabManager\Tabs_CPT;
use RedFoxWP\RedFoxTabManager\Abstracts\Abstract_API_Endpoint;

// Prevent direct access.
if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

/**
 * Available Tabs API class
 *
 * Handles operations for listing and searching available tabs.
 *
 * @since 1.0.0
 */
class Available_Tabs_API extends Abstract_API_Endpoint {

	/**
	 * Get the route base for this endpoint
	 *
	 * @since 1.0.0
	 * @access public
	 *
	 * @return string
	 */
	public function get_route_base() {
		return 'available-tabs';
	}

	/**
	 * Register REST API routes
	 *
	 * @since 1.0.0
	 * @access public
	 *
	 * @return void
	 */
	public function register_routes() {
		// Get available tabs.
		register_rest_route(
			self::NAMESPACE,
			'/' . $this->get_route_base(),
			array(
				'methods'             => \WP_REST_Server::READABLE,
				'callback'            => array( $this, 'get_available_tabs' ),
				'permission_callback' => array( $this, 'check_permissions' ),
				'args'                => array(
					'search'          => array(
						'type'              => 'string',
						'default'           => '',
						'validate_callback' => 'rest_validate_request_arg',
						'sanitize_callback' => 'sanitize_text_field',
						'description'       => __( 'Search term to filter tabs.', 'redfox-tab-manager' ),
					),
					'posts_per_page'  => array(
						'type'              => 'integer',
						'default'           => 20,
						'validate_callback' => function ( $param ) {
							return is_numeric( $param ) || '-1' === $param || -1 === $param;
						},
						'sanitize_callback' => function ( $param ) {
							return ( '-1' === $param || -1 === $param ) ? -1 : absint( $param );
						},
						'description'       => __( 'Number of tabs to return per page. Use -1 for all tabs.', 'redfox-tab-manager' ),
					),
					'page'            => array(
						'type'              => 'integer',
						'default'           => 1,
						'validate_callback' => function ( $param ) {
							return is_numeric( $param ) && $param >= 1;
						},
						'sanitize_callback' => 'absint',
						'description'       => __( 'Current page number for pagination.', 'redfox-tab-manager' ),
					),
					'orderby'         => array(
						'type'              => 'string',
						'default'           => 'title',
						'enum'              => array( 'title', 'date', 'modified', 'menu_order' ),
						'validate_callback' => 'rest_validate_request_arg',
						'sanitize_callback' => 'sanitize_text_field',
						'description'       => __( 'Sort tabs by field.', 'redfox-tab-manager' ),
					),
					'order'           => array(
						'type'              => 'string',
						'default'           => 'ASC',
						'enum'              => array( 'ASC', 'DESC' ),
						'validate_callback' => 'rest_validate_request_arg',
						'sanitize_callback' => 'sanitize_text_field',
						'description'       => __( 'Sort order.', 'redfox-tab-manager' ),
					),
					'include_content' => array(
						'type'              => 'boolean',
						'default'           => true,
						'validate_callback' => 'rest_validate_request_arg',
						'sanitize_callback' => 'rest_sanitize_boolean',
						'description'       => __( 'Whether to include tab content in response.', 'redfox-tab-manager' ),
					),
					'all_statuses'    => array(
						'type'              => 'boolean',
						'default'           => false,
						'validate_callback' => 'rest_validate_request_arg',
						'sanitize_callback' => 'rest_sanitize_boolean',
						'description'       => __( 'Whether to include tabs with all post statuses (draft, private, etc.).', 'redfox-tab-manager' ),
					),
				),
			)
		);
	}

	/**
	 * Get available tabs for assignment to products
	 *
	 * @since 1.0.0
	 * @access public
	 *
	 * @param \WP_REST_Request $request Request object.
	 * @return \WP_REST_Response|\WP_Error
	 */
	public function get_available_tabs( $request ) {
		$search          = $request->get_param( 'search' );
		$posts_per_page  = $request->get_param( 'posts_per_page' );
		$page            = $request->get_param( 'page' );
		$orderby         = $request->get_param( 'orderby' );
		$order           = $request->get_param( 'order' );
		$include_content = $request->get_param( 'include_content' );
		$all_statuses    = $request->get_param( 'all_statuses' );

		// Add enhanced validation.
		if ( -1 !== $posts_per_page && ( 1 > $posts_per_page || 100 < $posts_per_page ) ) {
			return $this->error_response(
				'invalid_posts_per_page',
				__( 'Posts per page must be -1 or between 1 and 100.', 'redfox-tab-manager' ),
				400
			);
		}

		// Search term validation.
		if ( ! empty( $search ) && strlen( $search ) < 2 ) {
			return $this->error_response(
				'invalid_search_term',
				__( 'Search term must be at least 2 characters long.', 'redfox-tab-manager' ),
				400
			);
		}

		// Page validation.
		if ( $page < 1 ) {
			return $this->error_response(
				'invalid_page',
				__( 'Page number must be 1 or greater.', 'redfox-tab-manager' ),
				400
			);
		}

		// Query RedFox Tabs.
		$args = array(
			'post_type'      => Tabs_CPT::CPT_NAME,
			'post_status'    => $all_statuses ? array( 'publish', 'draft', 'private', 'pending', 'future' ) : 'publish',
			'posts_per_page' => $posts_per_page,
			'paged'          => -1 === $posts_per_page ? 1 : $page, // Don't paginate if posts_per_page is -1.
			'orderby'        => $orderby,
			'order'          => $order,
			'fields'         => 'all', // Explicit field selection.
		);

		if ( ! empty( $search ) ) {
			$args['s'] = $search;
		}

		// Use WP_Query for better control.
		$query = new \WP_Query( $args );

		// Check for query errors.
		if ( is_wp_error( $query ) ) {
			return $this->error_response(
				'query_error',
				__( 'Database query failed. Please try again.', 'redfox-tab-manager' ),
				500
			);
		}

		if ( ! $query->have_posts() ) {
			$message = ! empty( $search )
				? __( 'No tabs found matching your search criteria.', 'redfox-tab-manager' )
				: __( 'No tabs found.', 'redfox-tab-manager' );

			return $this->success_response(
				array(),
				$message,
				200
			);
		}

		$available_tabs = array();
		foreach ( $query->posts as $tab ) {
			$tab_data = array(
				'id'       => $tab->ID,
				'title'    => $tab->post_title,
				'slug'     => $tab->post_name,
				'status'   => $tab->post_status,
				'date'     => $tab->post_date,
				'modified' => $tab->post_modified,
			);

			if ( $include_content ) {
				$tab_data['content'] = $tab->post_content;
				$tab_data['excerpt'] = wp_trim_words( wp_strip_all_tags( $tab->post_content ), 20, '...' );
			}

			$available_tabs[] = $tab_data;
		}

		// Prepare pagination metadata.
		$pagination = array(
			'current_page'   => -1 === $posts_per_page ? 1 : $page,
			'total_pages'    => -1 === $posts_per_page ? 1 : $query->max_num_pages,
			'total_items'    => $query->found_posts,
			'items_per_page' => -1 === $posts_per_page ? $query->found_posts : $posts_per_page,
			'has_next_page'  => -1 === $posts_per_page ? false : $page < $query->max_num_pages,
			'has_prev_page'  => -1 === $posts_per_page ? false : $page > 1,
		);

		wp_reset_postdata();

		return $this->success_response(
			$available_tabs,
			'',
			200,
			array( 'pagination' => $pagination )
		);
	}
}
