<?php
/**
 * Class Api file.
 *
 * @package Settings
 */

namespace WebToffee\CookieConsent\Lite\Admin\Modules\Settings\Api;

use WP_REST_Server;
use WP_Error;
use stdClass;
use WebToffee\CookieConsent\Lite\Includes\Rest_Controller;
use WebToffee\CookieConsent\Lite\Admin\Modules\Settings\Includes\Settings;
use WebToffee\CookieConsent\Lite\Admin\Modules\Settings\Includes\Controller;
use WebToffee\CookieConsent\Lite\Includes\Notice;

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

/**
 * Cookies API
 *
 * @class       Api
 * @version     3.0.0
 * @package     WebToffee
 * @extends     Rest_Controller
 */
class Api extends Rest_Controller {

	/**
	 * Endpoint namespace.
	 *
	 * @var string
	 */
	protected $namespace = 'wcc/v1';
	/**
	 * Route base.
	 *
	 * @var string
	 */
	protected $rest_base = 'settings';

	/**
	 * Constructor
	 */
	public function __construct() {
		add_action( 'rest_api_init', array( $this, 'register_routes' ), 10 );
	}
	/**
	 * Register the routes for cookies.
	 *
	 * @return void
	 */
	public function register_routes() {
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base,
			array(
				array(
					'methods'             => WP_REST_Server::READABLE,
					'callback'            => array( $this, 'get_items' ),
					'permission_callback' => array( $this, 'get_items_permissions_check' ),
					'args'                => $this->get_collection_params(),
				),
				array(
					'methods'             => WP_REST_Server::CREATABLE,
					'callback'            => array( $this, 'create_item' ),
					'permission_callback' => array( $this, 'create_item_permissions_check' ),
					'args'                => $this->get_endpoint_args_for_item_schema( WP_REST_Server::CREATABLE ),
				),
				'schema' => array( $this, 'get_public_item_schema' ),
			)
		);
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base . '/laws',
			array(
				array(
					'methods'             => WP_REST_Server::READABLE,
					'callback'            => array( $this, 'get_laws' ),
					'permission_callback' => array( $this, 'get_items_permissions_check' ),
					'args'                => $this->get_collection_params(),
				),
			)
		);
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base . '/info',
			array(
				array(
					'methods'             => WP_REST_Server::READABLE,
					'callback'            => array( $this, 'get_info' ),
					'permission_callback' => array( $this, 'get_items_permissions_check' ),
					'args'                => $this->get_collection_params(),
				),
			)
		);
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base . '/disconnect',
			array(
				array(
					'methods'             => WP_REST_Server::CREATABLE,
					'callback'            => array( $this, 'disconnect' ),
					'permission_callback' => array( $this, 'create_item_permissions_check' ),
					'args'                => $this->get_collection_params(),
				),
			)
		);
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base . '/cache/purge',
			array(
				array(
					'methods'             => WP_REST_Server::CREATABLE,
					'callback'            => array( $this, 'clear_cache' ),
					'permission_callback' => array( $this, 'create_item_permissions_check' ),
					'args'                => $this->get_collection_params(),
				),
			)
		);
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base . '/notices/(?P<notice>[a-zA-Z0-9-_]+)',
			array(
				array(
					'methods'             => WP_REST_Server::CREATABLE,
					'callback'            => array( $this, 'update_notice' ),
					'permission_callback' => array( $this, 'create_item_permissions_check' ),
					'args'                => $this->get_collection_params(),
				),
			)
		);
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base . '/reinstall',
			array(
				array(
					'methods'             => WP_REST_Server::CREATABLE,
					'callback'            => array( $this, 'install_missing_tables' ),
					'permission_callback' => array( $this, 'create_item_permissions_check' ),
					'args'                => $this->get_collection_params(),
				),
			)
		);
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base . '/initiatescan',
			array(
				array(
					'methods'             => WP_REST_Server::CREATABLE,
					'callback'            => array( $this, 'initiate_scan' ),
					'permission_callback' => array( $this, 'create_item_permissions_check' ),
					'args'                => $this->get_collection_params(),
				),
			)
		);
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base . '/reset',
			array(
				array(
					'methods'             => 'POST',
					'callback'            => array( $this, 'reset_settings' ),
					'permission_callback' => array( $this, 'create_item_permissions_check' ),
				),
			)
		);
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base . '/dismissnotice',
			array(
				array(
					'methods'             => WP_REST_Server::CREATABLE,
					'callback'            => array( $this, 'dismiss_migration_notice' ),
					'permission_callback' => array( $this, 'create_item_permissions_check' ),
					'args'                => $this->get_collection_params(),
				),
			)
		);
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base . '/renewconsentnotice',
			array(
				array(
					'methods'             => WP_REST_Server::CREATABLE,
					'callback'            => array( $this, 'show_renew_consent_notice' ),
					'permission_callback' => array( $this, 'create_item_permissions_check' ),
					'args'                => $this->get_collection_params(),
				),
			)
		);
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base . '/reviewdata',
			array(
				array(
					'methods'             => WP_REST_Server::CREATABLE,
					'callback'            => array( $this, 'review_data' ),
					'permission_callback' => array( $this, 'create_item_permissions_check' ),
					'args'                => $this->get_collection_params(),
				),
			)
		);
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base . '/export',
			array(
				array(
					'methods'             => 'POST',
					'callback'            => array( $this, 'export' ),
					'permission_callback' => array( $this, 'create_item_permissions_check' ),
				),
			)
		);
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base . '/import',
			array(
				array(
					'methods'             => 'POST',
					'callback'            => array( $this, 'import' ),
					'permission_callback' => array( $this, 'create_item_permissions_check' ),
				),
			)
		);
	}
	/**
	 * Get a collection of items.
	 *
	 * @param WP_REST_Request $request Full details about the request.
	 * @return WP_Error|WP_REST_Response
	 */
	public function get_items( $request ) {
		$object = new Settings();
		$data   = $object->get();
		return rest_ensure_response( $data );
	}
	/**
	 * Create a single cookie or cookie category.
	 *
	 * @param WP_REST_Request $request Full details about the request.
	 * @return WP_Error|WP_REST_Response
	 */
	public function create_item( $request ) {
		$data    = $this->prepare_item_for_database( $request );
		$context = ! empty( $request['context'] ) ? $request['context'] : 'view';
		$data    = $this->add_additional_fields_to_object( $data, $request );
		$data    = $this->filter_response_by_context( $data, $context );
		return rest_ensure_response( $data );
	}

	/**
	 * Fetch default laws from database
	 *
	 * @param array $request WP_REST_Request $request Full details about the request.
	 * @return array
	 */
	public function get_laws( $request = array() ) {
		$object = array(
			array(
				'slug'        => 'gdpr',
				'title'       => __( 'GDPR (General Data Protection Regulation)', 'webtoffee-cookie-consent' ),
				'description' => __( 'Continue with the GDPR template if most of your targeted audience are from the EU or UK. It creates a customizable banner that allows your visitors to accept/reject cookies or adjust their consent preferences.', 'webtoffee-cookie-consent' ),
				'tooltip'     => __(
					'Choose GDPR if most of your targeted audience are from the EU or UK.
					It creates a customizable banner that allows your visitors to accept/reject cookies or adjust their consent preferences.',
					'webtoffee-cookie-consent'
				),
			),
			array(
				'slug'        => 'ccpa',
				'title'       => __( 'CCPA (California Consumer Privacy Act)', 'webtoffee-cookie-consent' ),
				'description' => __( 'Choose CCPA if most of your targeted audience are from California or US. This will create a customizable banner with a “Do Not Sell My Personal Information” link that allows your visitors to refuse the use of cookies.', 'webtoffee-cookie-consent' ),
				'tooltip'     => __(
					'Choose CCPA if most of your targeted audience are from California or US.
					It creates a customizable banner with a “Do Not Sell My Personal Information” link that allows your visitors to refuse the use of cookies.',
					'webtoffee-cookie-consent'
				),
			),
			array(
				'slug'        => 'info',
				'title'       => __( 'INFO (Information Display Banner)', 'webtoffee-cookie-consent' ),
				'description' => __( 'Choose INFO if you do not want to block any cookies on your website. This will create a dismissible banner that provides some general information to your site visitors.', 'webtoffee-cookie-consent' ),
				'tooltip'     => __(
					'Choose Info if you do not want to block any cookies on your website.
						It creates a dismissible banner that provides some general info to your site visitors.',
					'webtoffee-cookie-consent'
				),
			),
		);
		$data   = $this->prepare_item_for_response( $object, $request );
		return rest_ensure_response( $data );
	}

	/**
	 * Get site info including the features allowed for the current plan.
	 *
	 * @param WP_REST_Request $request Full details about the request.
	 * @return WP_Error|WP_REST_Response
	 */
	public function get_info( $request ) {
		$args       = array();
		$registered = $this->get_collection_params();
		if ( isset( $registered['force'], $request['force'] ) ) {
			$args['force'] = (bool) $request['force'];
		}
		$response = Controller::get_instance()->get_info( $args );
		if ( empty( $response ) ) {
			$data = array();
		} else {
			$data = $this->prepare_item_for_response( $response, $request );
		}
		$objects = $this->prepare_response_for_collection( $data );
		return rest_ensure_response( $objects );
	}

	/**
	 * Clear cache of all the modules
	 *
	 * @return WP_Error|WP_REST_Response
	 */
	public function clear_cache() {
		$banner_controller   = new \WebToffee\CookieConsent\Lite\Admin\Modules\Banners\Includes\Controller();
		$category_controller = new \WebToffee\CookieConsent\Lite\Admin\Modules\Cookies\Includes\Category_Controller();
		$cookie_controller   = new \WebToffee\CookieConsent\Lite\Admin\Modules\Cookies\Includes\Cookie_Controller();
		$banner_controller->delete_cache();
		$category_controller->delete_cache();
		$cookie_controller->delete_cache();
		wp_cache_flush();
		$data = array( 'status' => true );
		return rest_ensure_response( $data );
	}

	/**
	 * Update the status of admin notices.
	 *
	 * @param object $request Request.
	 * @return WP_Error|WP_REST_Response
	 */
	public function update_notice( $request ) {
		$response = array( 'status' => false );
		$notice   = isset( $request['notice'] ) ? $request['notice'] : false;
		$expiry   = isset( $request['expiry'] ) ? intval( $request['expiry'] ) : 0;
		if ( $notice ) {
			Notice::get_instance()->dismiss( $notice, $expiry );
			$response['status'] = true;
		}
		return rest_ensure_response( $response );
	}

	/**
	 * Update the status of admin notices.
	 *
	 * @param object $request Request.
	 * @return WP_Error|WP_REST_Response
	 */
	public function install_missing_tables( $request ) {
		$missing_tables = wcc_missing_tables();
		if ( count( $missing_tables ) > 0 ) {
			do_action( 'wcc_reinstall_tables' );
			do_action( 'wcc_clear_cache' );
		}
		return rest_ensure_response( array( 'success' => true ) );
	}

	/**
	 * Update the status of admin notices.
	 *
	 * @param object $request Request.
	 * @return WP_Error|WP_REST_Response
	 */
	public function initiate_scan( $request ) {
		$missing_tables = wcc_missing_tables();
		if ( count( $missing_tables ) > 0 ) {
			do_action( 'wcc_reinstall_tables' );
			do_action( 'wcc_clear_cache' );
		}
		return rest_ensure_response( array( 'success' => true ) );
	}

	/**
	 * Reset plugin settings
	 *
	 * @since 3.0.0
	 *
	 * @return WP_Error|WP_REST_Response
	 */
	public function reset_settings() {
		return rest_ensure_response( Controller::get_instance()->reset() );
	}

	/**
	 * Update the status of admin migration notices.
	 *
	 * @param object $request Request.
	 * @return WP_Error|WP_REST_Response
	 */
	public function dismiss_migration_notice( $request ) {
		update_option( 'wcc_migration_notice_dismissed', true );
		return rest_ensure_response( array( 'success' => true ) );
	}
	/**
	 * Update the status of admin renew consent notices.
	 * @param array  $request Request params.
	 * @since 3.1.1
	 * @return WP_Error|WP_REST_Response
	 */
	public function show_renew_consent_notice( $request ) {
		return rest_ensure_response( Controller::get_instance()->update_renew_consent_notice( $request ) );
	}
	/**
	 * Update data related to review seeking banner.
	 *
	 * @param object $request Request.
	 * @return WP_Error|WP_REST_Response
	 */
	public function review_data( $request ) {
		return rest_ensure_response( Controller::get_instance()->update_review_data( $request ) );
	}
	/**
	 * Export settings.
	 * @since 3.3.0
	 * @return array
	 */
	public function export() {
		return rest_ensure_response( Controller::get_instance()->export_settings() );
	}
	/**
	 * Import settings.
	 *
	 * @since 3.3.0
	 * @return array
	 */
	public function import() {
		return rest_ensure_response( Controller::get_instance()->import_settings() );
	}
	/**
	 * Format data to provide output to API
	 *
	 * @param object $settings Object of the corresponding item Cookie or Cookie_Categories.
	 * @param array  $request Request params.
	 * @return array
	 */
	public function prepare_item_for_response( $settings, $request ) {
		$context = ! empty( $request['context'] ) ? $request['context'] : 'view';
		$data    = $this->add_additional_fields_to_object( $settings, $request );
		$data    = $this->filter_response_by_context( $data, $context );
		return rest_ensure_response( $data );
	}

	/**
	 * Prepare a single item for create or update.
	 *
	 * @param  WP_REST_Request $request Request object.
	 * @return stdClass
	 */
	public function prepare_item_for_database( $request ) {
		$object     = new Settings();
		$data       = $object->get();
		$schema     = $this->get_item_schema();
		$properties = isset( $schema['properties'] ) && is_array( $schema['properties'] ) ? $schema['properties'] : array();
		if ( ! empty( $properties ) ) {
			$properties_keys = array_keys(
				array_filter(
					$properties,
					function ( $property ) {
						return isset( $property['readonly'] ) && true === $property['readonly'] ? false : true;
					}
				)
			);
			foreach ( $properties_keys as $key ) {
				$value        = isset( $request[ $key ] ) ? $request[ $key ] : '';
				$data[ $key ] = $value;
			}
		}
		$object->update( $data );
		return $object->get();
	}

	/**
	 * Get the query params for collections.
	 *
	 * @return array
	 */
	public function get_collection_params() {
		return array(
			'context'  => $this->get_context_param( array( 'default' => 'view' ) ),
			'paged'    => array(
				'description'       => __( 'Current page of the collection.', 'webtoffee-cookie-consent' ),
				'type'              => 'integer',
				'default'           => 1,
				'sanitize_callback' => 'absint',
				'validate_callback' => 'rest_validate_request_arg',
				'minimum'           => 1,
			),
			'per_page' => array(
				'description'       => __( 'Maximum number of items to be returned in result set.', 'webtoffee-cookie-consent' ),
				'type'              => 'integer',
				'default'           => 10,
				'minimum'           => 1,
				'maximum'           => 100,
				'sanitize_callback' => 'absint',
				'validate_callback' => 'rest_validate_request_arg',
			),
			'search'   => array(
				'description'       => __( 'Limit results to those matching a string.', 'webtoffee-cookie-consent' ),
				'type'              => 'string',
				'sanitize_callback' => 'sanitize_text_field',
				'validate_callback' => 'rest_validate_request_arg',
			),
			'force'    => array(
				'type'        => 'boolean',
				'description' => __( 'Force fetch data', 'webtoffee-cookie-consent' ),
			),
		);
	}

	/**
	 * Get the Consent logs's schema, conforming to JSON Schema.
	 *
	 * @return array
	 */
	public function get_item_schema() {
		$schema = array(
			'$schema'    => 'http://json-schema.org/draft-04/schema#',
			'title'      => 'consentlogs',
			'type'       => 'object',
			'properties' => array(
				'id'                         => array(
					'description' => __( 'Unique identifier for the resource.', 'webtoffee-cookie-consent' ),
					'type'        => 'integer',
					'context'     => array( 'view' ),
					'readonly'    => true,
				),
				'site'                       => array(
					'description' => __( 'Unique identifier for the resource.', 'webtoffee-cookie-consent' ),
					'type'        => 'object',
					'context'     => array( 'view', 'edit' ),
				),
				'api'                        => array(
					'description' => __( 'Language.', 'webtoffee-cookie-consent' ),
					'type'        => 'object',
					'context'     => array( 'view', 'edit' ),
				),
				'account'                    => array(
					'description' => __( 'Language.', 'webtoffee-cookie-consent' ),
					'type'        => 'object',
					'context'     => array( 'view', 'edit' ),
				),
				'consent_logs'               => array(
					'description' => __( 'Language.', 'webtoffee-cookie-consent' ),
					'type'        => 'object',
					'context'     => array( 'view', 'edit' ),
				),
				'languages'                  => array(
					'description' => __( 'Language.', 'webtoffee-cookie-consent' ),
					'type'        => 'object',
					'context'     => array( 'view', 'edit' ),
				),
				'onboarding'                 => array(
					'description' => __( 'Language.', 'webtoffee-cookie-consent' ),
					'type'        => 'object',
					'context'     => array( 'view', 'edit' ),
				),
				'banners'                    => array(
					'description' => __( 'Selected banners.', 'webtoffee-cookie-consent' ),
					'type'        => 'object',
					'context'     => array( 'view', 'edit' ),
				),
				'translation_modal'          => array(
					'description' => __( 'Translation modal', 'webtoffee-cookie-consent' ),
					'type'        => 'object',
					'context'     => array( 'view', 'edit' ),
				),
				'renew_date'                 => array(
					'description' => __( 'Renew date.', 'webtoffee-cookie-consent' ),
					'type'        => 'object',
					'context'     => array( 'view', 'edit' ),
				),
				'google_consent_mode'        => array(
					'description' => __( 'Google Consent Mode.', 'webtoffee-cookie-consent' ),
					'type'        => 'object',
					'context'     => array( 'view', 'edit' ),
				),
				'migration_notice'           => array(
					'description' => __( 'Migrtaion notice', 'webtoffee-cookie-consent' ),
					'type'        => 'object',
					'context'     => array( 'view', 'edit' ),
				),
				'url_passthrough'            => array(
					'description' => __( 'URL Passthrough', 'webtoffee-cookie-consent' ),
					'type'        => 'object',
					'context'     => array( 'view', 'edit' ),
				),
				'gcm_debug_mode'             => array(
					'description' => __( 'GCM Debug mode', 'webtoffee-cookie-consent' ),
					'type'        => 'object',
					'context'     => array( 'view', 'edit' ),
				),
				'gtag_behavior'              => array(
					'description' => __( 'Google tag behavior', 'webtoffee-cookie-consent' ),
					'type'        => 'object',
					'context'     => array( 'view', 'edit' ),
				),
				'redact_ads_data'            => array(
					'description' => __( 'Redact ads data', 'webtoffee-cookie-consent' ),
					'type'        => 'object',
					'context'     => array( 'view', 'edit' ),
				),
				'renew_consent_notice'       => array(
					'description' => __( 'Renew consent notice', 'webtoffee-cookie-consent' ),
					'type'        => 'object',
					'context'     => array( 'view', 'edit' ),
				),
				'hide_banner_on_pages'       => array(
					'description' => __( 'Hide cookie banner on selected pages', 'webtoffee-cookie-consent' ),
					'type'        => 'object',
					'context'     => array( 'view', 'edit' ),
				),
				'no_cookie_scripts_to_block' => array(
					'description' => __( 'No cookie script list to block', 'webtoffee-cookie-consent' ),
					'type'        => 'object',
					'context'     => array( 'view', 'edit' ),
				),
				'review_reminder'            => array(
					'description' => __( 'Review reminder', 'webtoffee-cookie-consent' ),
					'type'        => 'object',
					'context'     => array( 'view', 'edit' ),
				),
				'microsoft_clarity'          => array(
					'description' => __( 'Microsoft Clarity', 'webtoffee-cookie-consent' ),
					'type'        => 'object',
					'context'     => array( 'view', 'edit' ),
				),
				'microsoft_uet'              => array(
					'description' => __( 'Microsoft UET ', 'webtoffee-cookie-consent' ),
					'type'        => 'object',
					'context'     => array( 'view', 'edit' ),
				),
				'gtm_template'               => array(
					'description' => __( 'GTM Template', 'webtoffee-cookie-consent' ),
					'type'        => 'object',
					'context'     => array( 'view', 'edit' ),
				),
			),
		);

		return $this->add_additional_fields_schema( $schema );
	}
} // End the class.
