<?php
namespace EVPB\DesignLibrary;

if ( !defined( 'ABSPATH' ) ) { exit; }

require_once EVPB_DIR_PATH . 'includes/DesignLibrary/ImageImport.php';

if( !class_exists( 'DesignLibrary' ) ) {
	class DesignLibrary {
		private $url = 'https://demo.pluginenvision.com';

		public function __construct() {
			add_action( 'wp_ajax_evpbDesignLibraryTaxonomies', [$this, 'evpbDesignLibraryTaxonomies'] );
			add_action( 'wp_ajax_evpbDesignLibraryTemplates', [$this, 'evpbDesignLibraryTemplates'] );
			add_action( 'wp_ajax_evpbDesignLibraryTemplateImport', [$this, 'evpbDesignLibraryTemplateImport'] );
		}

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

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

			$type = sanitize_text_field( wp_unslash( $_POST['type'] ?? 'patterns' ) );
			$tax = 'blocks' === $type ? 'block-name' : 'pattern-category';

			$response = wp_remote_get( $this->url . "/wp-json/wp/v1/templates/$type/taxonomies/templates-plugin,$tax" );
			$body = json_decode( wp_remote_retrieve_body( $response ) );
			wp_send_json_success( $body );
		}

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

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

			$type = sanitize_text_field( wp_unslash( $_POST['type'] ?? 'patterns' ) );
			$category = sanitize_text_field( wp_unslash( $_POST['category'] ?? '' ) );
			$block = sanitize_text_field( wp_unslash( $_POST['block'] ?? '' ) );
			$pageNumber = absint( wp_unslash( $_POST['pageNumber'] ?? 1 ) );
			$start = $pageNumber - 1;
			$search = sanitize_text_field( wp_unslash( $_POST['search'] ?? '' ) );

			$catFilter = 'blocks' === $type ? "&block=$block" : "&category=$category";

			try {
				$response = wp_remote_get( $this->url . "/wp-json/wp/v1/templates/$type/?plugin=envision-page-builder&start=$start&end=$pageNumber$catFilter&search=$search" );

				$body = json_decode( wp_remote_retrieve_body( $response ) );
				wp_send_json_success( $body );
			} catch ( \Throwable $th ) {
				wp_send_json_error( $th->getMessage() );
			}
		}

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

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

			try {
				$data = ( new \EVPB\DesignLibrary\ImageImport() )->maybeImportImages( wp_unslash( $_POST['original_content'] ?? '' ) );
				wp_send_json_success( $data );
			} catch ( \Throwable $th ) {
				wp_send_json_error( $th->getMessage() );
			}
		}
	}
	new DesignLibrary();
}
