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

namespace BwWinnersGlobalSite\API;

if ( ! class_exists( __NAMESPACE__ . '\Google_Sync_Controller' ) ) {
	/**
	 * Controller for BwWinnersGlobalSite Options routes and endpoints
	 */
	class Google_Sync_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 = 'google-sync';

			$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 . '/spreadsheets',
				array(
					'methods'             => array( 'GET' ),
					'callback'            => array( $this, 'get_spreadsheets' ),
					'permission_callback' => array( $this, 'permissions_check' ),
				)
			);

			register_rest_route(
				$this->namespace,
				$this->resource_route . '/credentials',
				array(
					'methods'             => array( 'GET' ),
					'callback'            => array( $this, 'get_credentials' ),
					'permission_callback' => array( $this, 'permissions_check' ),
				)
			);

			register_rest_route(
				$this->namespace,
				$this->resource_route . '/credentials',
				array(
					'methods'             => array( 'POST', 'PUT' ),
					'callback'            => array( $this, 'update_credentials' ),
					'permission_callback' => array( $this, 'permissions_check' ),
				)
			);

			register_rest_route(
				$this->namespace,
				$this->resource_route . '/task',
				array(
					'methods'             => array( 'GET' ),
					'callback'            => array( $this, 'get_task' ),
					'permission_callback' => array( $this, 'permissions_check' ),
				)
			);


			register_rest_route(
				$this->namespace,
				$this->resource_route . '/sync',
				array(
					'methods'             => array( 'POST' ),
					'callback'            => array( $this, 'manual_sync_start' ),
					'permission_callback' => array( $this, 'permissions_check' ),
				)
			);


			register_rest_route(
				$this->namespace,
				$this->resource_route . '/run',
				array(
					'methods'             => array( 'POST' ),
					'callback'            => array( $this, 'manual_sync_run' ),
					'permission_callback' => array( $this, 'permissions_check' ),
				)
			);


			register_rest_route(
				$this->namespace,
				$this->resource_route . '/cleanup',
				array(
					'methods'             => array( 'POST' ),
					'callback'            => array( $this, 'manual_sync_cleanup' ),
					'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' );
		}

		/**
		 * Updates the BwWinnersGlobalSite plugin get spreadsheet info
		 *
		 * @param WP_REST_Request $request        API request.
		 *
		 * @return WP_REST_Response|WP_Error|WP_HTTP_Response|mixed
		 */
		public function get_spreadsheets ( $request ) {
			global $bw_winners_global_site;

			$spreadsheets = $bw_winners_global_site->google_sync->get_spreadsheets();

			if ( empty( $spreadsheets ) ) {
				return (object) [];
			}

			return rest_ensure_response( $spreadsheets );
		}

		/**
		 * Updates the BwWinnersGlobalSite plugin get credentials info
		 *
		 * @param WP_REST_Request $request        API request.
		 *
		 * @return WP_REST_Response|WP_Error|WP_HTTP_Response|mixed
		 */
		public function get_credentials ( $request ) {
			global $bw_winners_global_site;

			$credentials = $bw_winners_global_site->google_sync->get_credentials();

			if ( empty( $credentials ) ) {
				return (object) [];
			}

			return rest_ensure_response( $credentials );
		}

		/**
		 * Updates the BwWinnersGlobalSite plugin save credentials file
		 *
		 * @param WP_REST_Request $request        API request.
		 *
		 * @return WP_REST_Response|WP_Error|WP_HTTP_Response|mixed
		 */
		public function update_credentials ( $request ) {
			global $bw_winners_global_site;

			$files = $request->get_file_params();

			try {
				$bw_winners_global_site->google_sync->save_google_credentials_file( $files['credentials'] );

				$data = array( 'message' => 'Success!' );
				return rest_ensure_response( $data );

			} catch ( \Throwable $e ) {
				$error = new WP_Error(
					'internal_server_error',
					$e->getMessage(),
					array( 'status' => 500 )
				);
				return rest_ensure_response( $error );
			}
		}

		/**
		 * Updates the BwWinnersGlobalSite plugin get credentials info
		 *
		 * @param WP_REST_Request $request        API request.
		 *
		 * @return WP_REST_Response|WP_Error|WP_HTTP_Response|mixed
		 */
		public function get_task ( $request ) {
			global $bw_winners_global_site;

			$task = $bw_winners_global_site->auto_sync_cron->get_task();

			if ( empty( $task ) ) {
				return (object) [];
			}

			return rest_ensure_response( $task );
		}


		/**
		 * Starts a manual sync
		 *
		 * @param WP_REST_Request $request        API request.
		 *
		 * @return WP_REST_Response|WP_Error|WP_HTTP_Response|mixed
		 */
		public function manual_sync_start ( $request ) {

			global $bw_winners_global_site;

			try {
				$response = $bw_winners_global_site->google_sync_tasks->init_task();
			} catch ( \Throwable $e ) {
				$response = $bw_winners_global_site->google_sync_tasks->fail_task( [], $e->getMessage() );
			}

			return rest_ensure_response( $response );
		}


		/**
		 * Runs a manual sync task
		 *
		 * @param WP_REST_Request $request        API request.
		 *
		 * @return WP_REST_Response|WP_Error|WP_HTTP_Response|mixed
		 */
		public function manual_sync_run ( $request ) {

			global $bw_winners_global_site;

			$task = $request->get_json_params();

			try {
				$response = $bw_winners_global_site->google_sync_tasks->sync_task( $task );
			} catch ( \Throwable $e ) {
				$response = $bw_winners_global_site->google_sync_tasks->fail_task( $task, $e->getMessage() );
			}

			return rest_ensure_response( $response );
		}

		/**
		 * Runs a manual sync cleanup step
		 *
		 * @param WP_REST_Request $request        API request.
		 *
		 * @return WP_REST_Response|WP_Error|WP_HTTP_Response|mixed
		 */
		public function manual_sync_cleanup ( $request ) {

			global $bw_winners_global_site;

			$task = $request->get_json_params();

			try {
				$response = $bw_winners_global_site->google_sync_tasks->clean_task( $task );
			} catch ( \Throwable $e ) {
				$response = $bw_winners_global_site->google_sync_tasks->fail_task( $task, $e->getMessage() );
			}

			return rest_ensure_response( $response );			
		}
	}
}
