<?php
/** API Site Options Controller
 *
 * @package BwWinnersGlobalSite
 * @subpackage API
 */

namespace BwWinnersGlobalSite\API;

if ( ! class_exists( __NAMESPACE__ . '\Options_Controller' ) ) {
	/**
	 * Controller for BwWinnersGlobalSite Options routes and endpoints
	 */
	class Options_Controller {

		/**
		 * REST API namespace
		 *
		 * @var string
		 */
		public $namespace;

		/**
		 * Controller's resource name
		 *
		 * @var string
		 */
		public $resource_name;

		/**
		 * Controller's resource route
		 *
		 * @var string
		 */
		public $resource_route;

		/**
		 * Initializes properties and adds hooks.
		 */
		public function __construct() {
			$this->namespace = \BwWinnersGlobalSite\API_NAMESPACE;

			$this->resource_name = 'options';

			$this->resource_route = '/' . $this->resource_name;

			add_action( 'rest_api_init', array( $this, 'register_routes' ) );
		}


		/**
		 * Registers routes for the BwWinnersGlobalSite Options
		 */
		public function register_routes() {

			register_rest_route(
				$this->namespace,
				$this->resource_route,
				array(
					'methods'             => 'GET',
					'callback'            => array( $this, 'get' ),
					'permission_callback' => array( $this, 'permissions_check' ),
				)
			);

			register_rest_route(
				$this->namespace,
				$this->resource_route,
				array(
					'methods'             => array( 'POST', 'PUT' ),
					'callback'            => array( $this, 'update' ),
					'permission_callback' => array( $this, 'permissions_check' ),
				)
			);
		}

		/**
		 * Returns true if user can use the BwWinnersGlobalSite Options Page features
		 *
		 * @return boolean
		 */
		public function permissions_check() {
			return current_user_can( 'manage_options' );
		}

		/**
		 * Gets the BwWinnersGlobalSite plugin options and constants
		 *
		 * @return WP_REST_Response|WP_Error|WP_HTTP_Response|mixed
		 */
		public function get() {
			$options = \BwWinnersGlobalSite\Options::get_options();

			return rest_ensure_response(
				$options
			);
		}

		/**
		 * Updates the BwWinnersGlobalSite plugin options and constants
		 *
		 * @param WP_REST_Request $request        API request.
		 *
		 * @return WP_REST_Response|WP_Error|WP_HTTP_Response|mixed
		 */
		public function update( $request ) {
			$data = $request->get_json_params();

			// Validate data before updating
			if ( empty( $data ) || ! is_array( $data ) ) {
				return new \WP_Error( 'invalid_data', 'Invalid options data provided', array( 'status' => 400 ) );
			}

			$options = \BwWinnersGlobalSite\Options::update_options( $data );

			return rest_ensure_response( $options );
		}
	}
}
