<?php //phpcs:ignore

/**
 * File: Goodmeet_Ajax.php
 *
 * The Goodmeet_Ajax class handles AJAX requests and provides functionalities for generating referral coupons.
 *
 * @package Goodme
 * @since   1.0.0
 */

namespace SOVLIX\GOODMEET;

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

if ( ! class_exists( 'Goodmeet_Ajax' ) ) {
	/**
	 * The Goodmeet_Ajax class handles AJAX requests and provides functionalities for generating referral coupons.
	 *
	 * @since 1.0.0
	 */
	class Goodmeet_Ajax {
		/**
		 * Goodmeet_Ajax constructor.
		 *
		 * Initializes the class and sets up AJAX request handlers.
		 */
		public function __construct() {
			add_action( 'wp_ajax_goodmeet_meeting_action', array( $this, 'handle_goodmeet_meeting_action' ) );
			add_action( 'wp_ajax_nopriv_goodmeet_meeting_action', array( $this, 'handle_goodmeet_meeting_action' ) );
			add_action( 'wp_ajax_goodmeet_meeting_list', array( $this, 'goodmeet_meeting_lists' ) );
			add_action( 'wp_ajax_nopriv_goodmeet_meeting_list', array( $this, 'goodmeet_meeting_lists' ) );
			add_action( 'wp_ajax_goodmeet_google_meeting_list', array( $this, 'goodmeet_google_meeting_lists' ) );
			add_action( 'wp_ajax_nopriv_goodmeet_google_meeting_list', array( $this, 'goodmeet_google_meeting_lists' ) );
			add_action( 'wp_ajax_goodmeet_reset_google_meet_credential', array( $this, 'reset_credential' ) );
			add_action( 'wp_ajax_goodmeet_check_google_meet_credential', array( $this, 'check_credential_exists' ) );
			add_action( 'wp_ajax_goodmeet_check_google_meet_permission', array( $this, 'goodmeet_check_google_meet_permission' ) );
			add_action( 'wp_ajax_goodmeet_get_link', array( $this, 'goodmeet_get_link' ) );
		}

		/**
		 * Handles AJAX requests for fetching meeting lists.
		 *
		 * This function verifies the nonce for security, fetches the list of meetings,
		 * and returns the meetings as a JSON response. It is intended to be used as a
		 * callback for AJAX requests in WordPress.
		 *
		 * @since 1.13.1
		 *
		 * @return void
		 */
		public function goodmeet_meeting_lists() {
			// Verify nonce for security.
			$nonce = isset( $_POST['nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['nonce'] ) ) : '';
			if ( ! wp_verify_nonce( $nonce, 'goodmeet_frontend_nonce' ) ) {
				wp_send_json_error( 'Invalid nonce.' );
			}

			$meetings = goodmeet_meetings();

			wp_send_json_success( $meetings );
		}

		/**
		 * Handles AJAX requests to fetch a list of Google Meet meetings.
		 *
		 * This function verifies the nonce for security, interacts with the Google Meet API
		 * through the `Goodmeet_Events` class, and returns the list of meetings in JSON format.
		 *
		 * @return void
		 *
		 * @throws WP_Error If the nonce verification fails.
		 */
		public function goodmeet_google_meeting_lists() {
			// Verify nonce for security.
			$nonce = isset( $_POST['nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['nonce'] ) ) : '';
			if ( ! wp_verify_nonce( $nonce, 'goodmeet_admin_nonce' ) ) {
				wp_send_json_error( 'Invalid nonce.' );
			}

			$google_api = new \SOVLIX\GOODMEET\Googlemeet\Goodmeet_Events();

			$google_meet_response = $google_api->get_all_meetings();

			wp_send_json_success( $google_meet_response );
		}

		/**
		 * Handle end meeting action
		 */
		public function handle_goodmeet_meeting_action() {
			// Verify nonce for security.
			$nonce = isset( $_POST['nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['nonce'] ) ) : '';
			if ( ! wp_verify_nonce( $nonce, 'goodmeet_frontend_nonce' ) ) {
				wp_send_json_error( 'Invalid nonce.' );
			}

			$response = '';

			// Retrieve and sanitize posted data.
			$meeting_id     = isset( $_POST['meeting_id'] ) ? sanitize_text_field( wp_unslash( $_POST['meeting_id'] ) ) : '';
			$post_id        = isset( $_POST['post_id'] ) ? sanitize_text_field( wp_unslash( $_POST['post_id'] ) ) : '';
			$meeting_status = isset( $_POST['meeting_status'] ) ? sanitize_text_field( wp_unslash( $_POST['meeting_status'] ) ) : '';

			if ( 'end' === $meeting_status ) {
				update_post_meta( $post_id, 'goodmeet_meeting_status', 'end' );
				$response = 'Meeting ended successfully.';
			}

			if ( 'resume' === $meeting_status ) {
				update_post_meta( $post_id, 'goodmeet_meeting_status', 'resume' );
				$response = 'Meeting resumed successfully.';
			}

			if ( 'start' === $meeting_status ) {
				update_post_meta( $post_id, 'goodmeet_meeting_start_status', 'start' );
				$response = 'Meeting started successfully.';
			}

			if ( 'stop' === $meeting_status ) {
				update_post_meta( $post_id, 'goodmeet_meeting_start_status', 'stop' );
				$response = 'Meeting stoped successfully.';
			}

			// Example: Respond with a success message.
			wp_send_json_success( $response );
		}

		/**
		 * Reset user credentials and tokens by deleting from database.
		 *
		 * Uses the Goodmeet_Meet class to handle the reset operation.
		 * Sends a JSON response with the operation result.
		 *
		 * @return void
		 */
		public function reset_credential() {
			// Verify nonce to prevent CSRF attacks.
			$nonce = isset( $_REQUEST['nonce'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['nonce'] ) ) : '';
			if ( ! wp_verify_nonce( $nonce, 'goodmeet_admin_nonce' ) ) {
				wp_send_json_error( __( 'Invalid nonce.', 'goodmeet' ) );
				return;
			}

			// Verify user permissions.
			if ( ! current_user_can( 'manage_options' ) ) {
				wp_send_json_error( __( 'You are not authorized to perform this operation.', 'goodmeet' ) );
				return;
			}

			// Get the Google Meet instance and reset credentials.
			$google_meet = Googlemeet\Goodmeet_Meet::get_instance();
			$result      = $google_meet->reset_credentials();

			// Send appropriate response based on the result.
			if ( $result['success'] ) {
				wp_send_json_success( implode( ' ', $result['messages'] ) );
			} else {
				wp_send_json_error( implode( ' ', $result['messages'] ) );
			}
		}

		/**
		 * Check if the user's credential exists in database.
		 *
		 * Uses the Goodmeet_Meet class to check credential existence.
		 * Sends a JSON response with the result.
		 *
		 * @return void
		 */
		public function check_credential_exists() {
			if ( ! current_user_can( 'manage_options' ) ) {
				wp_send_json_error( array( 'message' => __( 'You are not authorized to perform this operation.', 'goodmeet' ) ), 403 );
				return;
			}

			$google_meet = Googlemeet\Goodmeet_Meet::get_instance();

			if ( $google_meet->is_credential_loaded() ) {
				wp_send_json_success( array( 'message' => 'Credential exists' ) );
			} else {
				wp_send_json_error( array( 'message' => 'Credential not found' ) );
			}

			wp_die();
		}

		/**
		 * Retrieve the Google Meet consent screen URL.
		 *
		 * Uses the `Goodmeet_Meet` instance to generate and return the consent screen URL.
		 * Sends a JSON response with the URL or an error message.
		 *
		 * @return void
		 */
		public function goodmeet_get_link() {
			if ( ! current_user_can( 'manage_options' ) ) {
				wp_send_json_error( __( 'You are not authorized to perform this operation.', 'goodmeet' ), 403 );
				return;
			}

			$google_meet = Googlemeet\Goodmeet_Meet::get_instance();
			$link        = $google_meet->get_consent_screen_url();

			if ( ! empty( $link ) ) {
				wp_send_json_success( array( 'link' => $link ) );
			} else {
				wp_send_json_error( __( 'Failed to retrieve the consent screen URL.', 'goodmeet' ) );
			}
		}

		/**
		 * Check Google Meet permissions and update the plugin settings.
		 *
		 * Verifies if the Google Meet application is permitted.
		 * Updates the `goodmeet_google_meet_account` option based on the permission status.
		 * Sends a JSON response with the permission status or an error message.
		 *
		 * @return void
		 */
		public function goodmeet_check_google_meet_permission() {
			// Check if the user has sufficient permissions.
			if ( ! current_user_can( 'manage_options' ) ) {
				wp_send_json_error( array( 'message' => __( 'You are not authorized to perform this operation.', 'goodmeet' ) ), 403 );
				return;
			}

			// Initialize Google Meet instance.
			try {
				$google_meet = Googlemeet\Goodmeet_Meet::get_instance();
				$permission  = $google_meet->is_app_permitted();

				if ( $permission ) {
					update_option( 'goodmeet_google_meet_account', 'connected' );
				} else {
					update_option( 'goodmeet_google_meet_account', '' );
				}

				// Send success response with permission status.
				wp_send_json_success( array( 'permission' => $permission ) );
			} catch ( Exception $e ) {
				// Handle any exceptions and send an error response.
				update_option( 'goodmeet_google_meet_account', '' );
				wp_send_json_error( array( 'message' => $e->getMessage() ), 500 );
			}
		}
	}
}
