<?php
/**
 * Defines REST Subdivisions API
 *
 * @link  https://personalizewp.com
 * @since 3.5.0
 *
 * @package PersonalizeWP/
 * @subpackage PersonalizeWP/Admin/REST
 */

namespace PersonalizeWP\Admin\REST;

defined( 'ABSPATH' ) || exit; // Exit if accessed directly.

/**
 * Subdivisions Controller class.
 *
 * Provides a REST endpoint to fetch subdivision data for a given country,
 * used by the admin rules form for the cascading country/state dropdown.
 *
 * @extends WP_REST_Controller
 */
class Subdivisions_Controller extends \WP_REST_Controller {

	/**
	 * Endpoint namespace.
	 *
	 * @var string
	 */
	protected $namespace;

	/**
	 * Route base.
	 *
	 * @var string
	 */
	protected $rest_base = 'subdivisions';

	/**
	 * Initialize the class and set its properties.
	 *
	 * @param string $ns Namespace.
	 */
	public function __construct( $ns ) {
		$this->namespace = $ns;
	}

	/**
	 * Registers the routes for the subdivisions controller.
	 *
	 * @see register_rest_route()
	 */
	public function register_routes() {
		register_rest_route(
			"{$this->namespace}v1",
			'/' . $this->rest_base . '/(?P<country>[A-Z]{2})',
			array(
				array(
					'methods'             => \WP_REST_Server::READABLE,
					'callback'            => array( $this, 'get_subdivisions' ),
					'permission_callback' => array( $this, 'get_subdivisions_permissions_check' ),
					'args'                => array(
						'country' => array(
							'type'              => 'string',
							'required'          => true,
							'validate_callback' => function ( $param ) {
								return preg_match( '/^[A-Z]{2}$/', $param );
							},
							'sanitize_callback' => 'sanitize_text_field',
						),
					),
				),
			)
		);
	}

	/**
	 * Check permissions for the subdivisions endpoint.
	 *
	 * @param \WP_REST_Request $request Full details about the request.
	 *
	 * @return bool|\WP_Error
	 */
	public function get_subdivisions_permissions_check( $request ) { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundAfterLastUsed
		if ( current_user_can( 'manage_options' ) ) {
			return true;
		}

		return new \WP_Error( 'rest_forbidden', esc_html__( 'You do not have permission to access this data.', 'personalizewp' ), array( 'status' => 403 ) );
	}

	/**
	 * Get subdivisions for a specific country.
	 *
	 * @param \WP_REST_Request $request Full details about the request.
	 *
	 * @return \WP_REST_Response
	 */
	public function get_subdivisions( $request ) {
		$country      = $request->get_param( 'country' );
		$subdivisions = \personalizewp()->get_subdivisions( $country );
		asort( $subdivisions );

		$response = rest_ensure_response( $subdivisions );

		// Cache for 24 hours — subdivision data is static.
		$response->header( 'Cache-Control', 'max-age=86400' );

		return $response;
	}
}
