<?php
/**
 * Global Tabs API Endpoint Class
 *
 * Handles REST API endpoints for global tabs management.
 *
 * @package RedFoxWP\RedFoxTabManager
 * @since 1.0.0
 */

namespace RedFoxWP\RedFoxTabManager\API;

use RedFoxWP\RedFoxTabManager\Global_Tabs;
use RedFoxWP\RedFoxTabManager\Abstracts\Abstract_API_Endpoint;

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

/**
 * Global Tabs API class
 *
 * Handles operations for global tabs management including getting,
 * saving, and deleting global tabs.
 *
 * @since 1.0.0
 */
class Global_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 'global-tabs';
	}

	/**
	 * Check permissions for API requests
	 *
	 * Override to require manage_options capability for global tabs.
	 *
	 * @since 1.0.0
	 * @access public
	 *
	 * @param \WP_REST_Request $request Request object.
	 * @return bool|\WP_Error
	 */
	public function check_permissions( $request ) {
		// Check if user can manage options (admin level).
		if ( ! current_user_can( 'manage_options' ) ) {
			return new \WP_Error(
				'rest_forbidden',
				__( 'You do not have permission to access this resource.', 'redfox-tab-manager' ),
				array( 'status' => 403 )
			);
		}

		return true;
	}

	/**
	 * Register REST API routes
	 *
	 * @since 1.0.0
	 * @access public
	 *
	 * @return void
	 */
	public function register_routes() {
		// Get global tabs.
		register_rest_route(
			self::NAMESPACE,
			'/' . $this->get_route_base(),
			array(
				'methods'             => \WP_REST_Server::READABLE,
				'callback'            => array( $this, 'get_global_tabs' ),
				'permission_callback' => array( $this, 'check_permissions' ),
			)
		);

		// Save global tabs.
		register_rest_route(
			self::NAMESPACE,
			'/' . $this->get_route_base(),
			array(
				'methods'             => \WP_REST_Server::CREATABLE,
				'callback'            => array( $this, 'save_global_tabs' ),
				'permission_callback' => array( $this, 'check_permissions' ),
				'args'                => array(
					'tabs' => array(
						'type'              => 'array',
						'required'          => true,
						'validate_callback' => array( $this, 'validate_tabs_array' ),
						'sanitize_callback' => array( $this, 'sanitize_tabs_array' ),
						'description'       => __( 'Array of global tabs to save.', 'redfox-tab-manager' ),
					),
				),
			)
		);

		// Reset global tabs to defaults.
		register_rest_route(
			self::NAMESPACE,
			'/' . $this->get_route_base() . '/reset-to-defaults',
			array(
				'methods'             => \WP_REST_Server::CREATABLE,
				'callback'            => array( $this, 'reset_to_defaults' ),
				'permission_callback' => array( $this, 'check_permissions' ),
			)
		);
	}

	/**
	 * Get global tabs
	 *
	 * @since 1.0.0
	 * @access public
	 *
	 * @param \WP_REST_Request $request Request object.
	 * @return \WP_REST_Response|\WP_Error
	 */
	public function get_global_tabs( $request ) {
		$admin_global_tabs = Global_Tabs::get_instance();
		$tabs              = $admin_global_tabs->get_global_tabs();

		return $this->success_response( $tabs );
	}

	/**
	 * Save global tabs
	 *
	 * @since 1.0.0
	 * @access public
	 *
	 * @param \WP_REST_Request $request Request object.
	 * @return \WP_REST_Response|\WP_Error
	 */
	public function save_global_tabs( $request ) {
		$tabs = $request->get_param( 'tabs' );

		// Additional validation for tabs array.
		if ( empty( $tabs ) || ! is_array( $tabs ) ) {
			return $this->error_response(
				'invalid_tabs_data',
				__( 'Invalid tabs data provided.', 'redfox-tab-manager' ),
				400
			);
		}

		// Update the option.
		$updated = update_option( Global_Tabs::OPTION_NAME, $tabs );

		if ( ! $updated ) {
			return $this->error_response(
				'save_failed',
				__( 'Failed to save global tabs. Please try again.', 'redfox-tab-manager' ),
				500
			);
		}

		return $this->success_response(
			null,
			__( 'Global tabs saved successfully!', 'redfox-tab-manager' )
		);
	}

	/**
	 * Validate tabs array parameter
	 *
	 * @since 1.0.0
	 * @access public
	 *
	 * @param mixed $param Parameter value.
	 * @return bool
	 */
	public function validate_tabs_array( $param ) {
		if ( ! is_array( $param ) ) {
			return false;
		}

		// Check maximum array size to prevent abuse.
		if ( count( $param ) > 50 ) {
			return false;
		}

		// Validate each tab structure.
		foreach ( $param as $tab ) {
			if ( ! is_array( $tab ) ) {
				return false;
			}

			// Required fields.
			if ( ! isset( $tab['id'] ) || ! isset( $tab['title'] ) ) {
				return false;
			}

			// Validate ID format and length.
			if ( ! is_string( $tab['id'] ) || strlen( $tab['id'] ) > 50 || empty( trim( $tab['id'] ) ) ) {
				return false;
			}

			// Validate title length.
			if ( ! is_string( $tab['title'] ) || strlen( $tab['title'] ) > 200 || empty( trim( $tab['title'] ) ) ) {
				return false;
			}

			// Validate content length if present.
			if ( isset( $tab['content'] ) && ! $this->validate_content_length( $tab['content'], 50000 ) ) {
				return false;
			}

			// Validate optional fields if present.
			if ( isset( $tab['priority'] ) && ( ! is_numeric( $tab['priority'] ) || $tab['priority'] < 0 || $tab['priority'] > 999 ) ) {
				return false;
			}

			if ( isset( $tab['enabled'] ) && ! is_bool( $tab['enabled'] ) && ! in_array( $tab['enabled'], array( 0, 1, '0', '1', true, false ), true ) ) {
				return false;
			}

			if ( isset( $tab['type'] ) && ( ! is_string( $tab['type'] ) || strlen( $tab['type'] ) > 50 ) ) {
				return false;
			}

			if ( isset( $tab['source'] ) && ( ! is_string( $tab['source'] ) || strlen( $tab['source'] ) > 50 ) ) {
				return false;
			}

			if ( isset( $tab['redfoxwp_tab_id'] ) && ( ! is_numeric( $tab['redfoxwp_tab_id'] ) || $tab['redfoxwp_tab_id'] < 0 ) ) {
				return false;
			}
		}

		return true;
	}

	/**
	 * Sanitize tabs array parameter
	 *
	 * @since 1.0.0
	 * @access public
	 *
	 * @param mixed $param Parameter value.
	 * @return array
	 */
	public function sanitize_tabs_array( $param ) {
		if ( ! is_array( $param ) ) {
			return array();
		}

		// Limit array size for security.
		$param = array_slice( $param, 0, 50 );

		$sanitized_tabs = array();
		foreach ( $param as $tab ) {
			if ( ! is_array( $tab ) ) {
				continue;
			}

			// Skip tabs without required fields.
			if ( empty( $tab['id'] ) || empty( $tab['title'] ) ) {
				continue;
			}

			$sanitized_tab = array(
				'id'              => sanitize_key( substr( $tab['id'], 0, 50 ) ),
				'title'           => sanitize_text_field( substr( $tab['title'], 0, 200 ) ),
				'content'         => wp_kses_post( substr( $tab['content'] ?? '', 0, 50000 ) ),
				'priority'        => min( max( absint( $tab['priority'] ?? 10 ), 0 ), 999 ),
				'enabled'         => (bool) ( $tab['enabled'] ?? true ),
				'type'            => sanitize_text_field( substr( $tab['type'] ?? 'custom', 0, 50 ) ),
				'source'          => sanitize_text_field( substr( $tab['source'] ?? 'custom', 0, 50 ) ),
				'redfoxwp_tab_id' => isset( $tab['redfoxwp_tab_id'] ) ? absint( $tab['redfoxwp_tab_id'] ) : 0,
			);

			// Only add if required fields are not empty after sanitization.
			if ( ! empty( $sanitized_tab['id'] ) && ! empty( $sanitized_tab['title'] ) ) {
				$sanitized_tabs[] = $sanitized_tab;
			}
		}

		return $sanitized_tabs;
	}

	/**
	 * Reset global tabs to defaults
	 *
	 * @since 1.0.0
	 * @access public
	 *
	 * @param \WP_REST_Request $request Request object.
	 * @return \WP_REST_Response|\WP_Error
	 */
	public function reset_to_defaults( $request ) {
		$admin_global_tabs = Global_Tabs::get_instance();
		$default_tabs      = $admin_global_tabs->reset_to_defaults();

		if ( false === $default_tabs ) {
			return $this->error_response(
				'reset_failed',
				__( 'Failed to reset tabs to defaults. Please try again.', 'redfox-tab-manager' ),
				500
			);
		}

		return $this->success_response(
			$default_tabs,
			__( 'Global tabs have been reset to default WooCommerce tabs!', 'redfox-tab-manager' )
		);
	}
}
