<?php
/**
 * Mhub_MsTeams API Class
 *
 * This class manages the API functionality for Microsoft Teams integration.
 *
 * @package SOVLIX\MHUB\API
 */

namespace SOVLIX\MHUB\API;

use WP_REST_Controller;
use WP_REST_Server;
use WP_Error;

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

if ( ! class_exists( 'Mhub_MsTeams' ) ) {
	/**
	 * Mhub_MsTeams Class
	 */
	class Mhub_MsTeams extends WP_REST_Controller {
		/**
		 * Mhub_MsTeams constructor
		 */
		public function __construct() {
			$this->namespace = 'meetinghub/v2';
			$this->rest_base = 'msteams';
		}

		/**
		 * Register REST API routes for Microsoft Teams
		 *
		 * @since 1.0.0
		 */
		public function register_routes() {
			// Route for OAuth authorization
			register_rest_route(
				$this->namespace,
				'/' . $this->rest_base . '/auth',
				array(
					array(
						'methods'             => WP_REST_Server::READABLE,
						'callback'            => array( $this, 'get_auth_url' ),
						'permission_callback' => array( $this, 'check_permissions' ),
					),
				)
			);

			// Route for OAuth callback
			register_rest_route(
				$this->namespace,
				'/' . $this->rest_base . '/callback',
				array(
					array(
						'methods'             => WP_REST_Server::CREATABLE,
						'callback'            => array( $this, 'handle_oauth_callback' ),
						'permission_callback' => array( $this, 'check_permissions' ),
					),
				)
			);

			// Route for getting user info
			register_rest_route(
				$this->namespace,
				'/' . $this->rest_base . '/user',
				array(
					array(
						'methods'             => WP_REST_Server::READABLE,
						'callback'            => array( $this, 'get_user_info' ),
						'permission_callback' => array( $this, 'check_permissions' ),
					),
				)
			);

			// Route for creating meetings
			register_rest_route(
				$this->namespace,
				'/' . $this->rest_base . '/meetings',
				array(
					array(
						'methods'             => WP_REST_Server::CREATABLE,
						'callback'            => array( $this, 'create_meeting' ),
						'permission_callback' => array( $this, 'check_permissions' ),
					),
					array(
						'methods'             => WP_REST_Server::READABLE,
						'callback'            => array( $this, 'list_meetings' ),
						'permission_callback' => array( $this, 'check_permissions' ),
					),
				)
			);

			// Route for individual meeting operations
			register_rest_route(
				$this->namespace,
				'/' . $this->rest_base . '/meetings/(?P<id>[a-zA-Z0-9-]+)',
				array(
					array(
						'methods'             => WP_REST_Server::READABLE,
						'callback'            => array( $this, 'get_meeting' ),
						'permission_callback' => array( $this, 'check_permissions' ),
					),
					array(
						'methods'             => WP_REST_Server::EDITABLE,
						'callback'            => array( $this, 'update_meeting' ),
						'permission_callback' => array( $this, 'check_permissions' ),
					),
					array(
						'methods'             => WP_REST_Server::DELETABLE,
						'callback'            => array( $this, 'delete_meeting' ),
						'permission_callback' => array( $this, 'check_permissions' ),
					),
				)
			);

			// Route for disconnecting
			register_rest_route(
				$this->namespace,
				'/' . $this->rest_base . '/disconnect',
				array(
					array(
						'methods'             => WP_REST_Server::CREATABLE,
						'callback'            => array( $this, 'disconnect' ),
						'permission_callback' => array( $this, 'check_permissions' ),
					),
				)
			);

			// Route for clearing tokens (for re-authentication)
			register_rest_route(
				$this->namespace,
				'/' . $this->rest_base . '/clear-tokens',
				array(
					array(
						'methods'             => WP_REST_Server::CREATABLE,
						'callback'            => array( $this, 'clear_tokens' ),
						'permission_callback' => array( $this, 'check_permissions' ),
					),
				)
			);

			// Route for testing permissions
			register_rest_route(
				$this->namespace,
				'/' . $this->rest_base . '/test-permissions',
				array(
					array(
						'methods'             => WP_REST_Server::READABLE,
						'callback'            => array( $this, 'test_permissions' ),
						'permission_callback' => array( $this, 'check_permissions' ),
					),
				)
			);
		}

		/**
		 * Check if the current user has permission to edit posts.
		 *
		 * @return bool True if the current user can edit posts, false otherwise.
		 */
		public function check_permissions() {
			return current_user_can( 'edit_posts' );
		}

		/**
		 * Get Microsoft Teams authorization URL
		 *
		 * @param WP_REST_Request $request Request object.
		 * @return WP_REST_Response|WP_Error
		 */
		public function get_auth_url( $request ) {
			$api = \SOVLIX\MHUB\API\MsTeams_Api::get_instance();
			$auth_url = $api->get_auth_uri();

			if ( ! $auth_url ) {
				return new WP_Error(
					'msteams_auth_error',
					__( 'Unable to generate authorization URL. Please check your Microsoft Teams settings.', 'meetinghub' ),
					array( 'status' => 400 )
				);
			}

			return rest_ensure_response( array( 'auth_url' => $auth_url ) );
		}

		/**
		 * Handle OAuth callback
		 *
		 * @param WP_REST_Request $request Request object.
		 * @return WP_REST_Response|WP_Error
		 */
		public function handle_oauth_callback( $request ) {
			$api = \SOVLIX\MHUB\API\MsTeams_Api::get_instance();
			$result = $api->fetch_access_token();

			if ( ! $result ) {
				return new WP_Error(
					'msteams_callback_error',
					__( 'Failed to process OAuth callback.', 'meetinghub' ),
					array( 'status' => 400 )
				);
			}

			return rest_ensure_response( array( 'success' => true ) );
		}

		/**
		 * Get current user info
		 *
		 * @param WP_REST_Request $request Request object.
		 * @return WP_REST_Response|WP_Error
		 */
		public function get_user_info( $request ) {
			$api = \SOVLIX\MHUB\API\MsTeams_Api::get_instance();
			
			// Check if OAuth data exists first
			$oauth_data = get_option( 'mhub_msteams_global_oauth_data' );
			if ( empty( $oauth_data ) || empty( $oauth_data->access_token ) ) {
				return new WP_Error(
					'msteams_not_connected',
					__( 'Microsoft Teams is not connected. Please set up your credentials first.', 'meetinghub' ),
					array( 'status' => 200 )
				);
			}
			
			$user_info = $api->get_user_info();

			if ( ! $user_info ) {
				return new WP_Error(
					'msteams_user_error',
					__( 'Unable to fetch user information.', 'meetinghub' ),
					array( 'status' => 401 )
				);
			}

			return rest_ensure_response( $user_info );
		}

		/**
		 * Create a new meeting
		 *
		 * @param WP_REST_Request $request Request object.
		 * @return WP_REST_Response|WP_Error
		 */
		public function create_meeting( $request ) {
			$api = \SOVLIX\MHUB\API\MsTeams_Api::get_instance();
			$data = $request->get_json_params();

			$meeting = $api->create_meeting( $data );

			if ( ! $meeting ) {
				return new WP_Error(
					'msteams_create_error',
					__( 'Failed to create Microsoft Teams meeting.', 'meetinghub' ),
					array( 'status' => 400 )
				);
			}

			return rest_ensure_response( $meeting );
		}

		/**
		 * List meetings
		 *
		 * @param WP_REST_Request $request Request object.
		 * @return WP_REST_Response|WP_Error
		 */
		public function list_meetings( $request ) {
			$api = \SOVLIX\MHUB\API\MsTeams_Api::get_instance();
			$params = $request->get_query_params();

			$meetings = $api->list_meetings( $params );

			if ( ! $meetings ) {
				return new WP_Error(
					'msteams_list_error',
					__( 'Failed to fetch Microsoft Teams meetings.', 'meetinghub' ),
					array( 'status' => 400 )
				);
			}

			return rest_ensure_response( $meetings );
		}

		/**
		 * Get a specific meeting
		 *
		 * @param WP_REST_Request $request Request object.
		 * @return WP_REST_Response|WP_Error
		 */
		public function get_meeting( $request ) {
			$api = \SOVLIX\MHUB\API\MsTeams_Api::get_instance();
			$meeting_id = $request->get_param( 'id' );

			$meeting = $api->get_meeting( $meeting_id );

			if ( ! $meeting ) {
				return new WP_Error(
					'msteams_get_error',
					__( 'Failed to fetch Microsoft Teams meeting.', 'meetinghub' ),
					array( 'status' => 404 )
				);
			}

			return rest_ensure_response( $meeting );
		}

		/**
		 * Update a meeting
		 *
		 * @param WP_REST_Request $request Request object.
		 * @return WP_REST_Response|WP_Error
		 */
		public function update_meeting( $request ) {
			$api = \SOVLIX\MHUB\API\MsTeams_Api::get_instance();
			$meeting_id = $request->get_param( 'id' );
			$data = $request->get_json_params();

			$meeting = $api->update_meeting( $meeting_id, $data );

			if ( ! $meeting ) {
				return new WP_Error(
					'msteams_update_error',
					__( 'Failed to update Microsoft Teams meeting.', 'meetinghub' ),
					array( 'status' => 400 )
				);
			}

			return rest_ensure_response( $meeting );
		}

		/**
		 * Delete a meeting
		 *
		 * @param WP_REST_Request $request Request object.
		 * @return WP_REST_Response|WP_Error
		 */
		public function delete_meeting( $request ) {
			$api = \SOVLIX\MHUB\API\MsTeams_Api::get_instance();
			$meeting_id = $request->get_param( 'id' );

			$result = $api->delete_meeting( $meeting_id );

			if ( ! $result ) {
				return new WP_Error(
					'msteams_delete_error',
					__( 'Failed to delete Microsoft Teams meeting.', 'meetinghub' ),
					array( 'status' => 400 )
				);
			}

			return rest_ensure_response( array( 'success' => true ) );
		}

		/**
		 * Disconnect Microsoft Teams
		 *
		 * @param WP_REST_Request $request Request object.
		 * @return WP_REST_Response|WP_Error
		 */
		public function disconnect( $request ) {
			$api = \SOVLIX\MHUB\API\MsTeams_Api::get_instance();
			$api->revoke_access_token();

			return rest_ensure_response( array( 'success' => true ) );
		}

		/**
		 * Clear MS Teams tokens for re-authentication
		 *
		 * @param WP_REST_Request $request Request object.
		 * @return WP_REST_Response|WP_Error
		 */
		public function clear_tokens( $request ) {
			$api = \SOVLIX\MHUB\API\MsTeams_Api::get_instance();
			$api->clear_tokens();

			return rest_ensure_response( array( 'success' => true, 'message' => 'Tokens cleared. Please reconnect.' ) );
		}

		/**
		 * Test MS Teams permissions
		 *
		 * @param WP_REST_Request $request Request object.
		 * @return WP_REST_Response|WP_Error
		 */
		public function test_permissions( $request ) {
			$api = \SOVLIX\MHUB\API\MsTeams_Api::get_instance();
			$results = $api->test_permissions();

			return rest_ensure_response( $results );
		}
	}
}