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

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

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

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


/**
 * Consent logs API
 *
 * @class       Api
 * @version     3.0.0
 * @package     WebToffee\CookieConsent
 * @extends     Rest_Controller
 */
class Api extends Rest_Controller {

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

	/**
	 * 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 . '/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 . '/delete',
			array(
				array(
					'methods'             => 'POST',
					'callback'            => array( $this, 'delete' ),
					'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 ) {
		$args       = array();
		$registered = $this->get_collection_params();
		$objects    = array();
		$items      = array();
		$per_page   = 10;
		if ( isset( $registered['lang'], $request['lang'] ) ) {
			$args['lang'] = sanitize_text_field( $request['lang'] );
		}
		if ( isset( $registered['per_page'], $request['per_page'] ) ) {
			$args['per_page'] = (int) $request['per_page'];
			$per_page         = $args['per_page'];
		}
		if ( isset( $registered['paged'], $request['paged'] ) ) {
			$args['paged'] = (int) $request['paged'];
		}
		$items = Controller::get_instance()->get_items( $args );

		foreach ( $items['data'] as $item ) {
			$data      = $this->prepare_item_for_response( $item, $request );
			$objects[] = $this->prepare_response_for_collection( $data );
		}
		// Wrap the data in a response object.
		$response   = rest_ensure_response( $objects );
		$total_logs = (int) isset( $items['count'] ) ? $items['count'] : 0;
		$max_pages  = ceil( $total_logs / (int) $per_page );
		$response->header( 'X-WP-TotalPages', $max_pages );
		$response->header( 'X-WP-Total', $total_logs );
		return $response;
	}

	/**
	 * Create a single log
	 *
	 * @param WP_REST_Request $request Full details about the request.
	 * @return WP_Error|WP_REST_Response
	 */
	public function create_item( $request ) {
		$result = wp_verify_nonce( $request->get_header( 'x_wp_nonce' ), 'wp_rest' );
		if ( ! $result ) {
			return new WP_Error( 'rest_cookie_invalid_nonce', __( 'Cookie check failed', 'webtoffee-cookie-consent' ), array( 'status' => 403 ) );
		}
		if ( ! empty( $request['id'] ) ) {
			return new WP_Error(
				'wcc_rest_item_exists',
				__( 'Cannot create existing post.', 'webtoffee-cookie-consent' ),
				array( 'status' => 400 )
			);
		}
		$prepared_item = $this->prepare_item_for_database( $request );
		$object        = Controller::get_instance()->create_item( $prepared_item );
		$data          = $this->prepare_item_for_response( $object, $request );
		$response      = rest_ensure_response( $data );
		return $response;
	}

	/**
	 * Format data to provide output to API
	 *
	 * @param object $item Object of the corresponding item.
	 * @param array  $request Request params.
	 * @return array
	 */
	public function prepare_item_for_response( $item, $request ) {
		$data     = $this->get_formatted_item_data( $item );
		$context  = ! empty( $request['context'] ) ? $request['context'] : 'view';
		$data     = $this->add_additional_fields_to_object( $data, $request );
		$data     = $this->filter_response_by_context( $data, $context );
		$response = rest_ensure_response( $data );
		return $response;
	}
	/**
	 * Get formatted item data
	 *
	 * @param  object $item consentLog object.
	 * @return array
	 */
	protected function get_formatted_item_data( $item ) {
		return array(
			'id'           => isset( $item->id ) ? $item->id : '',
			'ip'           => isset( $item->ip ) ? sanitize_text_field( $item->ip ) : '',
			'log'          => isset( $item->log ) ? $item->log : '',
			'status'       => isset( $item->status ) ? $item->status : '',
			'consent_id'   => isset( $item->consent_id ) ? sanitize_text_field( $item->consent_id ) : '',
			'date_created' => isset( $item->date_created ) ? $item->date_created : '',
		);
	}
	/**
	 * Prepare a single item for create or update.
	 *
	 * @param  WP_REST_Request $request Request object.
	 * @return stdClass
	 */
	public function prepare_item_for_database( $request ) {
		$log    = new stdClass();
		$schema = $this->get_item_schema();
		$body   = ( null !== $request->get_body() ) ? json_decode( $request->get_body(), true ) : array();
		if ( isset( $body['consent_id'] ) && ! empty( $schema['properties']['consent_id'] ) ) {
			$log->consent_id = $body['consent_id'];
		}
		if ( isset( $body['log'] ) && ! empty( $schema['properties']['log'] ) ) {
			$log->log = $body['log'];
		}
		return $log;
	}
	/**
	 * 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',
			),
		);
	}
	/**
	 * 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(
				'ip'         => array(
					'description' => __( 'Visitor IP.', 'webtoffee-cookie-consent' ),
					'type'        => 'string',
					'context'     => array( 'view', 'edit' ),
				),
				'country'    => array(
					'description' => __( 'Visitor Country.', 'webtoffee-cookie-consent' ),
					'type'        => 'string',
					'context'     => array( 'view', 'edit' ),
				),
				'status'     => array(
					'description' => __( 'Consent status.', 'webtoffee-cookie-consent' ),
					'type'        => 'string',
					'context'     => array( 'view', 'edit' ),
				),
				'log'        => array(
					'description' => __( 'Log.', 'webtoffee-cookie-consent' ),
					'type'        => 'array',
					'context'     => array( 'view', 'edit' ),
				),
				'consent_id' => array(
					'description' => __( 'Unique visitor ID', 'webtoffee-cookie-consent' ),
					'type'        => 'string',
					'context'     => array( 'view', 'edit' ),
				),
			),
		);

		return $this->add_additional_fields_schema( $schema );
	}
	public function export( $request ) {
		return rest_ensure_response( Controller::get_instance()->export() );
	}
	public function delete( $request ) {
		return rest_ensure_response( Controller::get_instance()->delete() );
	}
	public function create_item_permissions_check( $request ) {
		return true;
	}
} // End the class.
