<?php

/**
 * Define the API End Points
 * Option name: IvrVP1
 * Option value: any text string
 */

namespace IvrVP1\Includes\Api;

use WP_REST_Controller;

if (!defined('ABSPATH')) exit(); // No direct access allowed


class ApiEndPoints extends WP_REST_Controller {

	protected $rest_namespace;
	protected $rest_base;

	public function __construct() {
		$this->rest_namespace = REST_NAMESPACE;
		$this->rest_base = '/' . REST_BASE;
		add_action('rest_api_init', [$this, 'register_routes']);
	} // end __construct()


	public function register_routes() {

		register_rest_route(
			$this->rest_namespace,
			$this->rest_base,
			[
				[
					'methods' => \WP_REST_Server::READABLE,
					'callback' => [$this, 'get_item'],
					'permission_callback' => [$this, 'permission_check'],
					'args' => []
				],
				[
					'methods' => \WP_REST_Server::CREATABLE,
					'callback' => [$this, 'update_item'],
					'permission_callback' => [$this, 'permission_check'],
					'args' => []
				]
			]
		);
	} // end register_routes()


	public function get_item($request) {
		$response = get_option('IvrVP1');
		return rest_ensure_response($response);
		
	} // end get_items()


	public function update_item($request) {


		// Convert the request data to a JSON string and sanitize it
		$dataArr = sanitize_text_field(json_encode($request->get_json_params()['data'])); 

		// Decode the JSON string into a PHP object
		$dataObj =  json_decode($dataArr, false); // true = array, false = object

		$dataArr2 = [$dataObj->personId => ['firstName' => $dataObj->firstName, 'lastName' => $dataObj->lastName]];


		error_log("========== vue-plugin-1 log ==============");
		error_log(print_r($dataArr, true));
		error_log(print_r($dataArr2, true));
		error_log("========== End: vue-plugin-1 log =========");


		$response = update_option('IvrVP1', $dataArr2);
		return $response;
		

	} // end update_items()


	public function permission_check() {
		if (current_user_can('edit_posts')) {
			return true;
		} else {
			return false;
		}
	} // end permission_check()


} // end class ApiEndPoints