<?php

if (!class_exists('BPLVFPlugin')) {

	class BPLVFPlugin {

		function __construct() {
			add_action('init', [$this, 'onInit']);
			add_action('enqueue_block_assets', [$this, 'load_block_scripts']);

			add_action('wp_ajax_bplvfPipeChecker', [$this, 'bplvfPipeChecker']);
			add_action('wp_ajax_nopriv_bplvfPipeChecker', [$this, 'bplvfPipeChecker']);
			add_action('admin_init', [$this, 'registerSettings']);
			add_action('rest_api_init', [$this, 'registerSettings']);
		}

		function bplvfPipeChecker() {
			$nonce = isset($_POST['_wpnonce']) ? sanitize_text_field(wp_unslash($_POST['_wpnonce'])) : null;

			if (!wp_verify_nonce($nonce, 'wp_ajax')) {
				wp_send_json_error('Invalid Request');
			}

			wp_send_json_success([
				'isPipe' => [
					'isPipe'   => bplvf()->can_use_premium_code() ?? false,
					'adminUrl' => admin_url()
				]
			]);
		}

		function registerSettings() {
			register_setting('bplvfUtils', 'bplvfUtils', [
				'show_in_rest' => [
					'name' => 'bplvfUtils',
					'schema' => ['type' => 'string']
				],
				'type' => 'string',
				'default' => wp_json_encode(['nonce' => wp_create_nonce('wp_ajax')]),
				'sanitize_callback' => 'sanitize_text_field'
			]);
		}

		public static function load_block_scripts() {
			$title = '';
			$id = '';
			$blog_page_id = get_option( 'page_for_posts' );
			if ( $blog_page_id ) {
				$id =  $blog_page_id;
				$title = get_the_title( $blog_page_id );
			}else{
				$id = get_the_ID();
				$title = get_the_title( get_the_ID() );
			}
			
			global $wp;
			$current_url = home_url(add_query_arg([], $wp->request));
			
			wp_localize_script('bplvf-voice-feedback-view-script', 'voiceRecorder', [
				'ajaxUrl' => admin_url('admin-ajax.php'),
				'nonce' => wp_create_nonce('voice_feedback_nonce'),
				'source_page' => $title,
				'source_url'  => $current_url
			]);
			wp_localize_script('bplvf-voice-feedback-editor-script', 'voiceRecorder', [
				'ajaxUrl' => admin_url('admin-ajax.php'),
				'nonce' => wp_create_nonce('voice_feedback_nonce'),
				'source_page' => $title,
				'source_url'  => $current_url
			]);
		}

		function onInit() {
            register_block_type(__DIR__ .  '/build');
		}
	}
	new BPLVFPlugin();
}